(R)-检查子字符串是否包含在较大的字符串中并更改值

问题描述 投票:0回答:1

[我正在尝试检查数据集中的所有字符值的列,这些列的值分别为:“ 1”,“ 2”,“ 12”,“ NAME1”,“ NAME2”,...

我正在尝试选择具有非数字名称的值,并将其更改为99。这是我到目前为止所尝试的:

install.packages("stringi")
library(stringi)
stacked_data$NewCol=ifelse(stri_detect_fixed(stacked_data$OldCol,"NAME")==TRUE,99,stacked_data)

我在运行此代码时收到此错误消息:

Error in table(stacked_data$NewCol) : 
attempt to make a table with >= 2^31 elements

有人可以帮我指出正确的方向吗?任何帮助,将不胜感激!谢谢!

r substring grepl stringi
1个回答
0
投票

在这种情况下,您无需使用ifelse(),只需替换这些情况:

replace(x, grepl("NAME", x, fixed = TRUE), "99")

[1] "1"  "2"  "12" "99" "99"

stri_detect_fixed()类似:

replace(x, stri_detect_fixed(x, "NAME"), "99")

样本数据:

x <- c("1","2","12","NAME1","NAME2")
© www.soinside.com 2019 - 2024. All rights reserved.