简体   繁体   English

如何将多个空列添加到具有0行的data.frame中?

[英]How to add multiple empty columns to a data.frame with 0 rows?

I can add columns to data.frame: 我可以在data.frame中添加列:

x <- head(iris)
y <- x[1:nrow(x) > 7, ]
x[c('NewCol1', 'NewCol2')] <- rep(c('a', 'b'), each = nrow(x))

For a data.frame with 0 row, it does not work: 对于具有0行的data.frame,它不起作用:

# > y
# [1] Sepal.Length Sepal.Width  Petal.Length Petal.Width  Species     
# <0 rows> (or 0-length row.names)

y[c('NewCol1', 'NewCol2')] <- rep(c('a', 'b'), each = nrow(y))

# Error in value[[jvseq[[jjj]]]] : subscript out of bounds

I found this, Add Columns to an empty data frame in R , but it doesn't help much. 我发现了这一点, 即在R中将列添加到空数据框中 ,但这并没有太大帮助。

expected output: 预期输出:

# > y
# [1] Sepal.Length Sepal.Width  Petal.Length Petal.Width  Species      NewCol1      NewCol2
# <0 rows> (or 0-length row.names)

Consider the following code which creates an empty data frame: 考虑以下代码,该代码创建一个空的数据框:

df <- data.frame(Ints=integer(),
                 Characters=character(),
                 stringsAsFactors=FALSE)

One way to add a new column to this empty data frame is to use cbind() : 向此空数据帧添加新列的一种方法是使用cbind()

df2 <- cbind(df, data.frame(Stuff=character(),stringsAsFactors=FALSE))

> df2
[1] Ints       Characters Stuff     
<0 rows> (or 0-length row.names)

Then just add your data as you normally would, eg 然后像往常一样添加您的数据,例如

> df2[1,] <- c(1, "hello", "world")
> df2
  Ints Characters Stuff
1    1      hello world

As you mentioned, this might cause a casting problem in the Ints column. 如您所述,这可能会导致在Ints列中出现转换问题。 Assigning each column by itself avoids this, eg 单独分配每列可以避免这种情况,例如

df2$Ints <- c(1:5)
df2$Stuff <- c("one", "two", "three", "four", "five")

Or, you could use something like read.table to bring in your data, and explicitly assign the classes that way. 或者,您可以使用read.table之类的数据来引入数据,并以这种方式显式分配类。

We can use read.table by setting col.names parameter 我们可以通过设置col.names参数来使用read.table

read.table(text = "",col.names =  c(names(y), c("New_Col1", "New_Col2")))

#Sepal.Length Sepal.Width  Petal.Length Petal.Width  Specie   New_Col1  New_Col2   
#<0 rows> (or 0-length row.names)

We can also set our desired class by using the colClasses parameter 我们还可以使用colClasses参数设置所需的类

read.table(text = "",col.names =  c(names(y), c("New_Col1", "New_Col2")), 
                colClasses = c(sapply(y, class), "character", "character"))

So in this case the two new variables will get character class. 因此,在这种情况下,这两个新变量将获得character类。

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

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