gpt4 book ai didi

使用 data.table 删除字符串的一部分

转载 作者:行者123 更新时间:2023-12-04 09:45:13 25 4
gpt4 key购买 nike

我有一个包含一些字符串的数据表,我在其中找到重复的内容,我只需要识别某些行。我首先想用它来识别某些行(并基于它创建一个新变量。比我想在我的例子中去掉那部分(x))。

我知道有不使用 data.table 的解决方案。然而,问题是我要更好地学习 data.table,我需要 %chin% 的增强时间性能,这就是为什么我喜欢学习以 data.table 方式设置它。

c <- c("a", "b (x)", "c", "d (x)")
d <- c(1, 2, 3, 4)

c_name <- "string"
d_name <- "numeric"

df <- data.frame(c,d)
names(df) <- c(c_name,d_name)
setDT(df)

#Now comes the part where I want to create a new variable "Newvar" that only has text, if no "(x)" is in (%chin%) the string variable c:
df[ !( c %chin% c("(x)")) , Newvar:="had (x)"]
#My code does not work. It just takes All Rows.

#Next I want to remove all parts with (x) in string var c:
df[ ( c %chin% c("(x)")) , c ]
#this does not work like this.

我没有收到任何错误消息,但我的最终数据集应该如下所示:

#Final data set generation:

# 1) manually searching for (x)
Newvar <- c("", "had (x)","", "had (x)" )
# 2) "renaming" the string variable c
df$string <- gsub("\\(x\\)*", "", df$string)

#so actually the solution should be:
df$string <- c("a", "b", "c", "d")

但是在我的实际问题中,我这辈子都无法手动编写任何代码:D

最佳答案

%chin% 执行完整字符串的精确匹配,就像 %in% 一样,但速度更快。您正在尝试将其用于字符串内的部分匹配。要在 字符串中匹配模式,请使用 grep(或 grepl,它返回一个 logical,这对这种情况)。

c
# [1] "a" "b (x)" "c" "d (x)"
c %chin% "(x)"
# [1] FALSE FALSE FALSE FALSE
grepl("(x)", c, fixed = TRUE)
# [1] FALSE TRUE FALSE TRUE

如果您改用 grepl,我认为您的代码会按预期工作。我使用 fixed = TRUE 因为我们匹配的是一个精确的模式,而不是一个正则表达式。

我也觉得很奇怪,你特意将 c 列命名为 “string”,但你总是使用 c ,向量,而不是 df$stringdata.table 中的列。我建议修改为

# old
df[ !( c %chin% c("(x)")) , Newvar:="had (x)"]
# new: use `grepl` instead of `%chin%`, and `string` instead of `c`
df[ !grepl("(x)", string, fixed = TRUE) , Newvar:="had (x)"]

关于使用 data.table 删除字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57042648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com