如果我的数据框(df)如下所示:

Name        State
John Smith  MI
John Smith  WI
Jeff Smith  WI

我想将WI的John Smith重命名为“John Smith1”。什么是SQL语句的最干净的R等价形式?
update df
set Name = "John Smith1"
where Name = "John Smith"
and State = "WI"

最佳答案

df <- data.frame(Name=c('John Smith', 'John Smith', 'Jeff Smith'),
                 State=c('MI','WI','WI'), stringsAsFactors=F)

df <- within(df, Name[Name == 'John Smith' & State == 'WI'] <- 'John Smith1')

> df
         Name State
1  John Smith    MI
2 John Smith1    WI
3  Jeff Smith    WI

**编辑**

进行了编辑,添加了您可以将任何您喜欢的内容放入表达式内:
df <- within(df, {
    f <- Name == 'John Smith' & State == 'WI'
    Name[f] <- 'John Smith1'
    State[f] <- 'CA'
})

关于r - 根据其他列中的条件更新一个列中的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28650957/

10-12 13:57