如果 b 列包含条件字符串,则更改值列 a

Change value column a if column b contains conditional string

这个问题给我带来了很多麻烦,尽管它应该很快被修复。我有一个包含列 id 和 poster 的数据集。如果 id 值包含某个字符串,我想更改海报的值。请参阅以下数据:

test_df

id                   poster
143537222999_2054    Kevin
143115551234_2049    Dave
14334_5334           Eric
1456322_4334         Mandy
143115551234_445633  Patrick
143115551234_4321    Lars
143537222999_56743   Iris

我想得到

test_df

id                   poster
143537222999_2054    User
143115551234_2049    User
14334_5334           Eric
1456322_4334         Mandy
143115551234_445633  User
143115551234_4321    User
143537222999_56743   User

两列都是字符。如果 id 值包含“143537222999”或“143115551234”,我想将海报的值更改为 "User"。我试过以下代码:

匹配within/which

test_df <- within(test_df, poster[match('143115551234', test_df$id) | match('143537222999', test_df$id)] <- 'User')

这段代码没有给我任何错误,但它没有改变海报栏中的任何值。当我在其中替换时,出现错误:

test_df <- which(test_df, poster[match('143115551234', test_df$id) | match('143537222999', test_df$id)] <- 'User')
Error in which(test_df, poster[match("143115551234", test_df$id) |  : 
  argument to 'which' is not logical

匹配不同的变体

test_df <- test_df[match(id, test_df, "143115551234") | match(id, test_df, "143537222999"), test_df$poster] <- 'User'

这段代码给我错误:

Error in `[<-.data.frame`(`*tmp*`, match(id, test_df, "143115551234") |  : 
  missing values are not allowed in subscripted assignments of data frames
In addition: Warning messages:
1: In match(id, test_df, "143115551234") :
  NAs introduced by coercion to integer range
2: In match(id, test_df, "143537222999") :
  NAs introduced by coercion to integer range

在查找这个 error 之后,我发现 R 中的整数是 32 位的,整数的最大值是 2147483647。我不确定为什么会收到此错误,因为 R声明我的专栏是一个字符。

> lapply(test_df, class)

$poster
[1] "character"

$id
[1] "character"

Grepl

test_df[grepl("143115551234", id | "143537222999", id), poster := "User"]

此代码引发错误:

Error in `:=`(poster, "User") : could not find function ":="

我不确定修复此错误的最佳方法是什么,我尝试了多种变体并不断遇到不同的错误。

我之前在这里尝试了多个 that asked 的多个答案,但我仍然无法修复一些错误。

greplifelse一起使用:

df$poster <- ifelse(grepl("143537222999|143115551234", df$id), "User", df$poster)

Demo

您可以尝试使用 grepl

df[grepl('143115551234|143537222999', df$id),"poster"] <- "User"

因此,海报栏中与上述匹配的所有内容都被替换为 "User"

> df[grepl('143115551234|143537222999', df$id),"poster"] <- "User"
> df
                   id poster
1   143537222999_2054   User
2   143115551234_2049   User
3          14334_5334   Eric
4        1456322_4334  Mandy
5 143115551234_445633   User
6   143115551234_4321   User
7  143537222999_56743   User