编辑
:更改为OP新的可复制示例,根据OP的问题陈述提出两条建议;
library(data.table)
DT <- data.table(ID = c("b","b","b","a","a","c"),
a = 1:6, b = 7:12, c = 13:18)
colnamer1 <- function(newcolumname, datatable) {
## do calculations on dt
## create a column with whatever string is passed via 'newcolumnname'
set(datatable, j = newcolumname, value = 42)
}
colnamer2 <- function(newcolumname, datatable) {
## do calculations on dt
## create a column with whatever string is passed via 'newcolumnname'
dt[, (newcolumname) := 42]
}
colnamer1("name_me", DT)
colnamer2("name_me_too", DT)
DT
# ID a b c name_me name_me_too
# 1: b 1 7 13 42 42
# 2: b 2 8 14 42 42
# 3: b 3 9 15 42 42
# 4: a 4 10 16 42 42
# 5: a 5 11 17 42 42
# 6: c 6 12 18 42 42
一个可能的
data.frame
解决方案?尽管自从采用
data.table
我的
数据帧
-ING有点生锈。当你的问题涉及到
数据帧
.
df <- data.frame(ID = c("b","b","b","a","a","c"),
a = 1:6, b = 7:12, c = 13:18)
df_colnamer <- function(name_me, df) {
new_df <- df
new_df[[name_me]] <- 42
new_df
}
new_df <- df_colnamer("foo", df)
new_df
# ID a b c foo
# 1 b 1 7 13 42
# 2 b 2 8 14 42
# 3 b 3 9 15 42
# 4 a 4 10 16 42
# 5 a 5 11 17 42
# 6 c 6 12 18 42