【问题标题】:R - subsetting a data frame in a for loopR - 在 for 循环中对数据帧进行子集化
【发布时间】:2015-06-20 00:25:25
【问题描述】:

我试图在 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]
  ... 
}

很遗憾,子设置不起作用。当我使用 a&lt;- weather[which(weather$season %in% "summer") , ,drop=TRUE] 它运行良好。这也不能正常工作:

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

有人发现我的代码有问题吗?谢谢。

【问题讨论】:

  • 试试split(weather, weather$season)。最好将所有数据集保存在一个列表中,而不是将它们分散到全球环境中。

标签: r for-loop dataframe subset


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 2020-11-30
    • 2021-08-10
    • 2021-07-05
    • 1970-01-01
    • 2018-09-15
    • 2017-07-27
    相关资源
    最近更新 更多