【发布时间】:2018-11-16 23:15:49
【问题描述】:
这个问题给我带来了很多麻烦,尽管它应该很容易解决。我有一个包含 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”,我想将海报的值更改为“用户”。我尝试了以下代码:
在其中匹配
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 ":="
我不确定修复此错误的最佳方法是什么,我尝试了多种变体并不断遇到不同的错误。
【问题讨论】: