如果我的数据框(df)如下所示:
Name State
John Smith MI
John Smith WI
Jeff Smith WI
Run Code Online (Sandbox Code Playgroud)
我想从WI"John Smith1"重命名John Smith.什么是SQL语句中最干净的R等价物?
update df
set Name = "John Smith1"
where Name = "John Smith"
and State = "WI"
Run Code Online (Sandbox Code Playgroud)
Zel*_*ny7 24
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
Run Code Online (Sandbox Code Playgroud)
Dat*_*neR 10
单程:
df[df$Name == "John_Smith" & df$State == "WI", "Name"] <- "John_Smith1"
Run Code Online (Sandbox Code Playgroud)
使用的另一种方式dplyr
:
df %>% mutate(Name = ifelse(State == "WI" & Name == "John_Smith", "John_Smith1", Name))
Run Code Online (Sandbox Code Playgroud)
注意:正如David Arenburg所说,第一栏不应该是一个因素.为此,读取数据集stringsAsFactors = FALSE
.