我正在使用示例data airquality,我希望将数据帧拆分为几部分,其中month介于5-10之间,month是其他值。
我所拥有的:
aq <- na.omit(airquality)
aq$MonthF <- factor(aq$Month) # Make the month a factor我尝试的(拆分):
aq_s <- split(aq, aq$MonthF %in% c(5:10))
aq_n <- split(aq, aq$MonthF %in% c(1:4, 11:12))我试过了(子集):
aq_s <- subset(aq, MonthF %in% c(5:10))
aq_n <- subset(aq, MonthF %in% c(1:4, 11:12))结果:
> head(aq_n)
data frame with 0 columns and 6 rows在查看了其他堆栈溢出问题后,我仍然无法找到答案。如何正确地将此数据帧拆分为两组?
发布于 2017-05-08 12:08:22
正如@akrun提到的,我没有正确检查数据:
unique(aq$Month) # [1] 5 6 7 8 9所以仍然要回答这个问题,但是假设我想根据5个月、7个月到9个月来拆分数据,这是可行的:
aq_s <- subset(aq, MonthF %in% c(5, 7:9))
aq_n <- subset(aq, MonthF %in% c(6))
unique(aq_s$MonthF)
# [1] 5 7 8 9
# Levels: 5 6 7 8 9
unique(aq_n$MonthF)
# [1] 6
# Levels: 5 6 7 8 9发布于 2017-05-08 12:06:19
尝试执行unique(aq$Month)。您将看到数据集中唯一的月份是5-9月。
此外,这里有一个使用dplyr的解决方案:aq_s <- aq %>% filter( MonthF %in% c(5:10) ) aq_n <- aq %>% filter( MonthF %in% c(1:4, 11:12) )
同样,aq_n应该为空,因为数据帧中没有匹配的记录。
https://stackoverflow.com/questions/43839499
复制相似问题