我试图在for循环中对数据帧进行子集化以创建更小的data.frame。这是我的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
我想为每个季节(包含所有列)提取data.frame。这是我的代码:
for (season in seasons){
a<- weather[which(weather$season %in% season[1]) , ,drop=TRUE]
...
}
不幸的是,子设置没有&#39;工作。当我使用
a<- weather[which(weather$season %in% "summer") , ,drop=TRUE]
它完美无缺。这也不能正常工作:
season <- "summer"
a<- weather[which(weather$season %in% season[1]) , ,drop=TRUE]
有没有人看到我的代码有问题?谢谢。
答案 0 :(得分:1)
适用于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)
}