我实际上是在尝试创建一些代码来检测列中的值是否包含"%"。如果是,将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中,可以使用replace
和grepl
。
df <- transform(df,unit = replace(unit, grepl('%', variable, fixed = TRUE), '%'))
或
df$unit[grepl('%', df$variable, fixed = TRUE)] <- '%'