我正在尝试向我添加列data.table,其中名称是动态的.另外,我需要by在添加这些列时使用参数.例如:
test_dtb <- data.table(a = sample(1:100, 100), b = sample(1:100, 100), id = rep(1:10,10))
cn <- parse(text = "blah")
test_dtb[ , eval(cn) := mean(a), by = id]
# Error in `[.data.table`(test_dtb, , `:=`(eval(cn), mean(a)), by = id) :
# LHS of := must be a single column name when with=TRUE. When with=FALSE the LHS may be a vector of column names or positions.
Run Code Online (Sandbox Code Playgroud)
另一种尝试:
cn <- "blah"
test_dtb[ , cn := mean(a), by = id, with …Run Code Online (Sandbox Code Playgroud) A) 而不是这个 (where cars <- data.table(cars))
cars[ , .(`Totals:`=.N), by=speed]
Run Code Online (Sandbox Code Playgroud)
我需要这个
strColumnName <- "Totals:"
cars [ , strColumnName = .N, by=speed]
Run Code Online (Sandbox Code Playgroud)
怎么做?
B)类似(更一般的情况) - 而不是这个:
cars[ dist > 50, .(`Totals:`=.N, x=dist*100), by=speed]
Run Code Online (Sandbox Code Playgroud)
我需要这个:
strFactor <- "dist"
cars[ strFactor > 50, .(`Totals:`=.N, x=strFactor*100), by=speed]
Run Code Online (Sandbox Code Playgroud)
这个问题是关于在 data.table 中分配/引用列名变量的一般方法,即在“j”(RHS 和 LHS)以及“i”和“by”中 - 动态。当在代码中的其他地方选择时这是必需的(例如,用户我在闪亮的应用程序中输入它们)
C) 涉及 i,j 和 by 的一般情况 - 而不是这样:
cars[ dist > 50, .(`Totals x Factor: ` = .N * dist), by=speed]
Run Code Online (Sandbox Code Playgroud)
我需要这个:
strFactor <- "dist";
strNewVariable <- "Totals x …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用字符变量作为新列的名称以及by.
library(data.table)
dt <- data.table(g = rep(1:3, 4), xa = runif(12), xb = runif(12))
# desired output
dt[, .(sa = mean(xa)), by = g]
g sa
1: 1 1.902360
2: 2 2.149041
3: 3 2.586044
Run Code Online (Sandbox Code Playgroud)
问题是以下代码仍然返回整个 data.table,而没有减少到 g 的唯一值。
cn <- paste0('s', 'a')
# returns all rows
dt[, (cn) := mean(xa), by = g][]
g xa xb sa
1: 1 0.3423699 0.81447505 0.4755900
2: 2 0.0932055 0.06853225 0.5372602
3: 3 0.2486223 0.13286546 0.6465111
4: 1 0.6942175 0.66405944 0.4755900 …Run Code Online (Sandbox Code Playgroud) 我有一个包含10列的数据表.
town
tc
one
two
three
four
five
six
seven
total
Run Code Online (Sandbox Code Playgroud)
需要为我使用的"一"到"总"列生成平均值,
DTmean <- DT[,(lapply(.SD,mean)),by = .(town,tc),.SDcols=3:10]
Run Code Online (Sandbox Code Playgroud)
这会生成均值,但我希望列名称后缀为"_mean".我们应该怎么做?希望前两列保持与"town"和"tc"相同.我尝试了以下但是然后它将所有"one"重命名为"total"到"_mean"
for (i in 3:10) {
setnames(DTmean,i,paste0(names(i),"_mean"))
}
Run Code Online (Sandbox Code Playgroud)