如何根据条件替换行?

时间:2017-09-07 15:47:02

标签: r if-statement dataframe

这是一个非常简单的请求,但我无法绕过它。我已经创建了一个标志变量(0,1),如果flag == 1,我想在有条件的情况下将一列的值替换为另一列。

这是一个可重复的示例和我的错误代码:

if_else(q46$flag==1,q46$name==q46$positions,q46$name==q46$name)

set.seed(123)
q46 <- data.frame(flag=sample(0:1,100,replace=T),
       name=sample(c('Bob','Susan','Susan','Amy','Elliot'),100, replace=T),
      positions=sample(c('President','Agronomist','Preacher'),100,replace=T))

2 个答案:

答案 0 :(得分:2)

set.seed(123)
q46 <- data.frame(flag=sample(0:1,100,replace=T),
                  name=sample(c('Bob','Susan','Susan','Amy','Elliot'),100, replace=T),
                  positions=sample(c('President','Agronomist','Preacher'),100,replace=T))


q46$name = with(q46, ifelse(flag, as.character(positions), as.character(name)))

您需要将ifelse的输出分配到q46$name以替换它。 as.character转化是基于您的positionsname列是因素的假设(如果您在创建时未添加stringsAsFactors=FALSE,则会自动转换为因子data.frame)。

结果:

> head(q46, 10)
   flag       name  positions
1     0      Susan  President
2     1   Preacher   Preacher
3     0      Susan Agronomist
4     1 Agronomist Agronomist
5     1 Agronomist Agronomist
6     0     Elliot   Preacher
7     1 Agronomist Agronomist
8     1  President  President
9     1  President  President
10    0        Bob  President

答案 1 :(得分:2)

您可以尝试关注,同时,您的代码应该正常工作,只需添加stringsAsFactors = F,在创建data.frame if_else(q46$flag==1,q46$positions,q46$name)

q46$name[q46$flag==1]=q46$positions[q46$flag==1]

数据

 q46 <- data.frame(flag=sample(0:1,100,replace=T),
                      name=sample(c('Bob','Susan','Susan','Amy','Elliot'),100, replace=T),
                      positions=sample(c('President','Agronomist','Preacher'),100,replace=T),stringsAsFactors = F)