我有一个数据表,其中包含一些字符串。当我发现重复的东西时,我只需要用它们来识别某些行。首先我想要用它来识别特定的行(并创建一个基于此的新变量)。然后我想去掉该部分(在我的示例中为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
rm(list = ls())
这样的代码。我不想从您的问题中复制/粘贴代码并意外运行该行。 - Gregor Thomas