简体   繁体   English

如何一次性将多列添加到data.frame?

[英]How to add multiple columns to a data.frame in one go?

I have following dataframe and vector:我有以下数据框和向量:

ddf = data.frame(a=rep(1,10), b=rep(2,10))
xx = c("c", "d", "e", "f")

How can I new empty columns which are named with items in xx ?如何新建以 xx 中的项目命名的空列?

I tried following but it does not work:我尝试了以下但它不起作用:

ddf = cbind(ddf, data.frame(xx))
Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 10, 4

Following also does not work:以下也不起作用:

for(i in 1:length(xx)){
    ddf$(xx[i]) = ""  
}

Error: unexpected '(' in:
"for(i in 1:length(xx)){
ddf$("
 }
Error: unexpected '}' in "}"

This will get you there:这会让你到达那里:

ddf[xx] <- NA

#   a b  c  d  e  f
#1  1 2 NA NA NA NA
#2  1 2 NA NA NA NA
#3  1 2 NA NA NA NA
#...

You can't directly use something like ddf$xx because this will try to assign to a column called xx rather than interpreting xx .您不能直接使用ddf$xx类的东西,因为这会尝试分配给名为xx的列,而不是解释xx You need to use [ and [<- functions, using the square brackets when you are dealing with a character string/vector - like ddf["columnname"] or ddf[c("col1","col2")] , or a stored vector like your ddf[xx] .您需要使用[[<-函数,在处理字符串/向量时使用方括号 - 如ddf["columnname"]ddf[c("col1","col2")] ,或存储向量,如您的ddf[xx]

The reason why it selects columns is because data.frames are lists essentially:它选择列的原因是因为data.frames本质上是列表:

is.list(ddf)
#[1] TRUE

as.list(ddf)
#$a
# [1] 1 1 1 1 1 1 1 1 1 1
# 
#$b
# [1] 2 2 2 2 2 2 2 2 2 2

...with each column corresponding to a list entry. ...每列对应一个列表条目。 So if you don't use a comma to specify a row, like ddf["name",] or a column like ddf[,"name"] , you get the column by default.因此,如果您不使用逗号来指定行,如ddf["name",]或列如ddf[,"name"] ,则默认情况下您将获得该列。


In the case that you are working with a 0-row dataset, you can not use a value like NA as the replacement.如果您使用的是 0 行数据集,则不能使用NA之类的值作为替换。 Instead, replace with list(character(0)) where character(0) can be substituted for numeric(0) , integer(0) , logical(0) etc, depending on the class you want for your new columns.相反,替换为list(character(0)) ,其中character(0)可以替换为numeric(0)integer(0)logical(0)等,具体取决于您想要用于新列的类。

ddf <- data.frame(a=character())
xx <- c("c", "d", "e", "f")
ddf[xx] <- list(character(0))
ddf
#[1] a c d e f
#<0 rows> (or 0-length row.names)

This seems to succeed:这似乎成功了:

> cbind(ddf, setNames( lapply(xx, function(x) x=NA), xx) )
   a b  c  d  e  f
1  1 2 NA NA NA NA
2  1 2 NA NA NA NA
3  1 2 NA NA NA NA
4  1 2 NA NA NA NA
5  1 2 NA NA NA NA
6  1 2 NA NA NA NA
7  1 2 NA NA NA NA
8  1 2 NA NA NA NA
9  1 2 NA NA NA NA
10 1 2 NA NA NA NA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM