如果另一列中的值包含某个单词/字母,则插入该列中的值



我实际上是在尝试创建一些代码来检测列中的值是否包含"%"。如果是,将df$unit col设置为%。否则,什么也不做。

我尝试了下面的代码,但它返回所有行值的%,即使它们不包含%在里面。

我该如何修复它?

if(stringr::str_detect(df$variable, "%")) {

df$unit <- "%"

}

tidyverse方法

library(dplyr)
library(stringr)
df %>% 
mutate(unit = if_else(str_detect(variable,"%"),"%",unit))

尝试如下:

library(stringr)
df[str_detect(df$variable, "%"), 'unit'] <- "%"

不需要任何额外的库。

在base R中,可以使用replacegrepl

df <- transform(df,unit = replace(unit, grepl('%', variable, fixed = TRUE), '%'))

df$unit[grepl('%', df$variable, fixed = TRUE)] <- '%'

最新更新