重命名R data.table中的多个列

时间:2017-08-09 16:57:45

标签: r data.table

这与Henrik的这个问题有关 Assign multiple columns using := in data.table, by group

但是,如果我想创建具有给定列名的新data.table,而不是新列分配给现有列?

f <- function(x){list(head(x,2),tail(x,2))}
dt <- data.table(group=sample(c('a','b'),10,replace = TRUE),val=1:10)
> dt
    group val
 1:     b   1
 2:     b   2
 3:     a   3
 4:     b   4
 5:     a   5
 6:     b   6
 7:     a   7
 8:     a   8
 9:     b   9
10:     b  10

我希望通过调用函数f来获取带有预定义列名的新data.table:

dt[,c('head','tail')=f(val),by=group]

希望得到这个:

   group head tail
1:     a    1    8
2:     a    3   10
3:     b    2    6
4:     b    5    9

但它给了我一个错误。我能做的是创建表然后更改列名,但这似乎很麻烦:

> dt2 <- dt[,f(val),by=group]

> dt2
   group V1 V2
1:     a  1  8
2:     a  3 10
3:     b  2  6
4:     b  5  9

> colnames(dt2)[-1] <- c('head','tail')

> dt2
   group head tail
1:     a    1    8
2:     a    3   10
3:     b    2    6
4:     b    5    9

我可以通过一次通话做些什么吗?

1 个答案:

答案 0 :(得分:0)

按原样运行代码,这是我得到的错误:

for

问题是使用document.getElementById('course').onchange = function() { if (["BSCS", "BSIT","BSHRM","BSBM","BSTM"].indexOf(this.value) > -1) { document.getElementById("grade-11").setAttribute("disabled", true); document.getElementById("grade-12").setAttribute("disabled", true); } else { document.getElementById("grade-11").removeAttribute("disabled"); document.getElementById("grade-12").removeAttribute("disabled"); } } document.getElementById('course').onchange = function() { if (["STEM", "TOP","GAS","HUMSS"].indexOf(this.value) > -1) { document.getElementById("first-year").setAttribute("disabled", true); document.getElementById("second-year").setAttribute("disabled", true); document.getElementById("third-year").setAttribute("disabled", true); document.getElementById("fourth-year").setAttribute("disabled", true); } else { document.getElementById("first-year").removeAttribute("disabled"); document.getElementById("second-year").removeAttribute("disabled"); document.getElementById("third-year").removeAttribute("disabled"); document.getElementById("fourth-year").removeAttribute("disabled"); } } 代替dt[,c('head','tail')=f(val),by=group] # Error: unexpected '=' in "dt2[,c('head','tail')=" 进行分配。

关于想要新数据的问题。表:

=