0

im trying to subset a data frame in a for loop to create a smaller data.frame. This is my data.frame

day      rain in mm     temperature in °C     season     
1        201            20                    summer
2        156            18                    summer
3        56             -4                    winter
4        98             15                    spring

I want to extract a data.frame for each season (with all columns). Here is my code:

for (season in seasons){
  a<- weather[which(weather$season %in% season[1]) , ,drop=TRUE]
  ... 
}

Unfortunately, the sub-setting doesn' t work. When i use a<- weather[which(weather$season %in% "summer") , ,drop=TRUE] it works perfectly. Also this does not work properly:

season <- "summer"
a<- weather[which(weather$season %in% season[1]) , ,drop=TRUE]

Does anyone see the problem with my code? Thank you.

1
  • 2
    Try split(weather, weather$season). It is better to keep all the data sets in a single list instead of spreading them all over the global environment. Commented Apr 14, 2015 at 11:55

1 Answer 1

1

It works with dplyr.

library(dplyr)
mydf <- data.frame(day = c(1,2,3,4),
                   rain = c(201,156,56,98),
                   temperature = c(20,18,-4,15),
                   season = c("summer", "summer", "winter", "spring"))
seasons <- c("spring", "summer", "autumn", "winter")
for (sea in seasons) {
  a <- dplyr::filter(mydf, season == sea)
  print(a)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.