r - 根据其他列中的条件更新一个列中的值

标签 r

如果我的数据框(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/

相关文章:

r - data.table 具有时间窗口的不规则观测值的累积统计数据

R DataTable 重新编码许多变量

R 映射 : how do I fill the regions?

R: ggplot2 - switch 参数没有按预期工作

R创建列组合来自两列的信息

r - 什么时候在 R 中使用函数 'structure()'?

r - 在 R 中循环以仅将前导零添加到指定长度

r - 澄清 R 中分配给数组时复制数组语义

旋转椭圆的标绘点得到一个圆

r - 使用 R 重命名文件