在R中的数据表中命名列

时间:2014-11-21 19:52:26

标签: r data.table

我有两个数据表,D1和D2。 D1是20乘181,D2是181乘1.我想将D1列的名称更改为D2中的值。我使用以下代码,但我收到一个错误:

for(i in 1 : ncol(D1) ){ names(D1)[i] <- c("D2[i,1]")

错误:'closure'类型的对象不是子集表。

请您告诉我该怎么办才能让它发挥作用?

1 个答案:

答案 0 :(得分:-1)

我不会说数据表,但这是一个适用于数据框的解决方案,应该有希望概括。策略是使用这样一个事实:你可以用另一个向量填充一个向量,而不必使用循环。

 # make the example data sets
 D1 <- as.data.frame(matrix(data=(1:(20*181)), nrow=20, ncol=181))
 D2 <- data.frame(name=paste0("Name_",(1:181)))

 # make a copy of D1
 D1_named <- D1

 # the vector of D1 names is replaced by the value in D2
 # (both vectors must be of the same length)
 names(D1_named) <- D2$name