[英]Populate new column in R from other columns based on conditional statement
I have a data frame (data.frame(test)) in R with the following information. 我在R中有一个数据框(data.frame(test)),其中包含以下信息。
Columns1 | Column2 | Column3
1 | 11 | 33
3 | 34 | 56
4 | 24 | 23
5 | 74 | 64
3 | 45 | 52
2 | 54 | 53
1 | 76 | 92
I am trying to create a new column that is populated by the data in columns 2 and 3 based on a conditional statement of column 1. 我正在尝试创建一个新列,该列由第2列和第3列中的数据填充,基于第1列的条件语句。
I cannot seem to figure out how to write the appropriate conditional. 我似乎无法弄清楚如何编写适当的条件。
if (test$column1 == 3 || test$column1 == 2 || test$column1 == 1) {
test$Newcolumn = test$column1
} else {
test$NewColumn = test$column2
}
The final result should look like this: 最终结果应如下所示:
Columns1 | Column2 | Column3 | NewColumn
1 | 11 | 33 | 11
3 | 34 | 56 | 33
4 | 24 | 23 | 23
5 | 74 | 64 | 64
3 | 45 | 52 | 45
2 | 54 | 53 | 54
1 | 76 | 92 | 76
With dplyr
, assuming mydf
is your dataframe: 使用
dplyr
,假设mydf
是您的数据帧:
mydf %>% mutate(newColumn = ifelse(column1 %in% 1:3, column2, column3)) -> res
I assumed there is a typo in your question and you intended to assign column2
value to newColumn
in case the condition is met. 我假设您的问题中存在拼写错误,并且您打算在满足条件的情况下将
column2
值分配给newColumn
。
解决方案“像ifelse这样简单的ifelse(在%c(1,2,3)中测试$ column1%,测试$ column2,测试$ column3)” - 由joel.wilson工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.