我有一个数据框:
a = c(2, 3, 5, 4)
b = as.character(c("dogs are loving", "cats are the best", "we prefer cats", "dogs are sweet"))
df = data.frame(a, b)
print(df)
a b
2 dogs are loving
3 cats are the best
5 we prefer cats
4 dogs are sweet
我想更改df $ b,使其变为:
a b
2 dogs are loving
3 cats
5 cats
4 dogs are sweet
我知道我可以使用grepl来查明字符单元格是否包含单词cats ......
grepl("cats", df$b, ignore.case=TRUE)
...但我不知道如何使用它来将角色单元格更改为“猫”。
答案 0 :(得分:4)
试试这段代码:
df$b <- as.character(df$b)
df$b[grepl('cats', df$b)] <- 'cats'
答案 1 :(得分:3)
df = data.frame(a, b, stringsAsFactors = F)
df$b[grepl('cats', df$b)] <- 'cats'
grepl('cats', df$b)
创建一个逻辑向量,您可以使用它来有条件地应用更改。
我忘了最初包含stringsAsFactors = F
。使用此命令将消除许多令人头疼的问题,我希望这是默认设置。
答案 2 :(得分:0)
另一种选择:
df$b <- as.character(df$b)
df$b <- gsub(".*cats.*", "cats", df$b)
使用df$b[grepl('cats', df$b)] <- 'cats'
检查时,与microbenchmark
相比,更快
> microbenchmark(df$b <- gsub(".*cats.*", "cats", df$b), df$b[grepl('cats', df$b)] <- 'cats', times=10000L)
Unit: microseconds
expr min lq mean median uq max
df$b <- gsub(".*cats.*", "cats", df$b) 36.870 38.771 52.04216 39.911 59.2965 2040.421
df$b[grepl("cats", df$b)] <- "cats" 40.291 42.953 59.55412 44.473 66.8990 3087.998
neval
10000
10000