如何在R列中按列添加列到空白数据框?

时间:2014-01-14 11:08:06

标签: r dataframe add multiple-columns

我尝试创建一个data.fame,然后在这个data.frame中添加一些列。

我尝试使用代码,但它不起作用:

test.dim <- as.data.frame(matrix(nrow=0, ncol=4))
names <- c("A", "B", "C", "D")
colnames(test.dim) <- names

for (i in 1:4) {
    name = names[i]
    # do some calculations, at last get another data.fame named x.data

    mean.data <- apply(x.data, 1, mean)
    test.dim[, name] <- mean.data

}

1 个答案:

答案 0 :(得分:0)

通常会有一个data.frame(称之为df),只需调用df$newColName = valuesdf[,newColNames] = frame_of_values即可添加帧。

您的问题表明您正在将值的创建与将它们放入数据框(我不建议这样)分开。但是,如果你真的想从零行零col框架开始,这里有一些选择:

colnamesToAdd = LETTERS[1:4]
test.dim = data.frame(  matrix(rep(NA),length(colnamesToAdd),nrow=1)   )
colnames(test.dim) = colnamesToAdd
test.dim = test.dim[-1,]

另一种选择:

colnamesToAdd = LETTERS[1:4]
test.dim = data.frame("USELESS" = NA)
test.dim[,colnamesToAdd] = NA
test.dim = test.dim[-1,-1]

如果您希望在表格中添加均值并针对每个因素重复它:

library(data.table); 
test.dim = data.table("FACTOR" = sample(letters[1:4],100,replace=TRUE), "VALUE" = runif(100), "MEAN" = NA)
means = test.dim[,list(AVG=mean(VALUE)),by="FACTOR"]
# without data.table: by(test.dim$VALUE, test.dim$FACTOR, mean)
for(x in 1:nrow(means)) { test.dim$MEAN[test.dim$FACTOR==means$FACTOR[x]] = means$AVG[x] } # normally I would use the foreach package instead of this last for loop