[英]R data.table: How do you create a new column with a name from a string?
I have a vector of strings, and I need to create one new column in my data.table for each of them. 我有一个字符串向量,我需要在data.table中为每个字符串创建一个新列。 Like so: 像这样:
dt <- data.table(a = c(1,2,3), b = c(4,5,6))
column_names <- c("x", "y", "z")
I want to do something like this: 我想做这样的事情:
for (column_name in column_names) {
dt[, column_name := paste0(column_name, a, b)]
}
This should result in something like this: 这应该导致如下结果:
a | b | x | y | z
-----------------------
1 | 4 | x14 | y14 | z14
2 | 5 | x25 | y25 | z25
3 | 6 | x36 | y36 | z36
But instead, it tries to create a column with the name "column_name" 3 times. 但是,它尝试创建3次名称为“ column_name”的列。 How do I get around this? 我该如何解决?
You may want to use .SD
instead of a loop. 您可能需要使用.SD
而不是循环。 Replace log
with whatever function you want to apply to the columns. 将log
替换为要应用于列的任何功能。
mtcars <- as.data.table(mtcars)
columnstolog <- c('mpg', 'cyl', 'disp', 'hp')
mtcars[, (columnstolog) := lapply(.SD, log), .SDcols = columnstolog]
Here's a quick and dirty way of doing this: 这是一种快速而肮脏的方法:
CODE 码
library(data.table)
dt <- as.data.table(mtcars)
col_names <- c("col1", "col2", "col3")
for(i in 1:length(col_names)){
dt[, paste(col_names[i]) := i]
}
OUTPUT 输出值
> head(dt)
mpg cyl disp hp drat wt qsec vs am gear carb col1 col2 col3
1: 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 1 2 3
2: 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 1 2 3
3: 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 1 2 3
4: 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 1 2 3
5: 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 1 2 3
6: 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 1 2 3
I'm sure there're more elegant ways of doing this. 我敢肯定有更优雅的方法可以做到这一点。
Try wrapping column_name
in parenthesis. 尝试将column_name
括在括号中。 For example: 例如:
mtcars <- as.data.table(mtcars)
for (col in names(mtcars)) {
mtcars[, (col) := 1]
}
So as long as you can retrieve the assigned value in the for-loop, that should get you what you want. 因此,只要您可以在for循环中检索分配的值,就可以得到所需的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.