![](/img/trans.png)
[英]Split a dataframe column in multiple columns based on multiple occurrences of a separator in R
[英]R dataframe split based on multiple factor values (multiple months)
我正在使用示例數據airquality
,我想將數據airquality
拆分為每月介於5到10之間以及月份為其他值的地方。
我有的:
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
在查看其他stackoverflow問題后,我仍然無法弄清楚。 如何正確地將此數據幀分為2組?
如@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
嘗試執行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
應該為空,因為數據幀中沒有匹配的記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.