我已经提到过:
-
如何根据另一列的条件语句将因子列添加到数据框? https://stackoverflow.com/questions/16570302/how-to-add-a-factor-column-to-dataframe-based-on-a-conditional-statement-from-an,
-
如何在R编程中根据条件将列添加到数据框中 https://stackoverflow.com/questions/15016723/how-to-add-column-into-a-dataframe-based-on-condition-in-r-programming and
-
R:添加对三列进行条件检查的列? https://stackoverflow.com/questions/6557714/r-add-column-with-condition-check-on-three-columns .
所有示例均基于对其他列中的数值向量或 NA 进行测试并添加新变量。这是一个简短的可重现示例:
x <- c("dec 12", "jan 13", "feb 13", "march 13", "apr 13", "may 13",
"june 13", "july 13", "aug 13", "sep 13", "oct 13", "nov 13")
y <- c(234, 678, 534, 122, 179, 987, 872, 730, 295, 450, 590, 312)
df<-data.frame(x,y)
我想加上“冬天”df$x
= 十二月 |一月 |二月,“春天”,三月|四月|五月,“夏天”和“秋天”。
I tried
df$season <- ifelse(df[1:3, ], "winter", ifelse(df[4:6, ], "spring",
ifelse(df[7:9, ], "summer", "autumn")))
我知道这是一种非常低效的做事方式,但我是一个新手,也是一个混杂者。它返回了错误:
Error in ifelse(df[1:3, ], "winter", ifelse(df[4:6, ], "spring",
ifelse(df[7:9, : (list) object cannot be coerced to type 'logical'
如果同一个数据框有数千行,并且我想循环遍历它并根据一年中的月份为季节创建一个新变量,我该怎么做?我提到:”循环遍历数据框以添加依赖于其他列中的变量的列 https://stackoverflow.com/questions/18336343/looping-through-a-data-frame-to-add-a-column-depending-variables-in-other-column“但这是循环并设置一个数学运算符来创建新变量。我尝试了外部资源:R 邮件列表中的一个帖子 http://r.789695.n4.nabble.com/R-help-Adding-a-column-in-a-data-frame-with-multiple-conditions-td4645072.html and TalkStats 论坛上的一个帖子 http://www.talkstats.com/showthread.php/30924-Adding-a-new-column-in-R-data-frame-with-values-conditional-on-another-column。然而,两者都是基于数值变量和条件。