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

时间:2018-06-07 06:37:25

标签: r replace match grepl

这个问题给我带来了很多麻烦,即使它应该定期修复。我有一个列id和海报的数据集。如果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",OR" 143115551234"。我尝试过以下代码:

匹配/

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 ":="

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

此前我已尝试过来自多个questions that were asked的多个答案,但我仍然无法修复错误。

2 个答案:

答案 0 :(得分:1)

greplifelse

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

enter image description here

Demo

答案 1 :(得分:0)

您可以使用grepl尝试此操作。

df[grepl('143115551234|143537222999', df$id),"poster"] <- "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