如何向具有0行的data.frame中添加多个空列?
我可以向data.frame添加列:如何向具有0行的data.frame中添加多个空列?,r,dataframe,R,Dataframe,我可以向data.frame添加列: x <- head(iris) y <- x[1:nrow(x) > 7, ] x[c('NewCol1', 'NewCol2')] <- rep(c('a', 'b'), each = nrow(x)) x考虑以下创建空数据帧的代码: df <- data.frame(Ints=integer(), Characters=character(), strin
x <- head(iris)
y <- x[1:nrow(x) > 7, ]
x[c('NewCol1', 'NewCol2')] <- rep(c('a', 'b'), each = nrow(x))
x考虑以下创建空数据帧的代码:
df <- data.frame(Ints=integer(),
Characters=character(),
stringsAsFactors=FALSE)
然后像平常一样添加数据,例如
> df2[1,] <- c(1, "hello", "world")
> df2
Ints Characters Stuff
1 1 hello world
或者,您可以使用类似于read.table
的方法来引入数据,并以这种方式显式分配类。我们可以通过设置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)
read.table(text = "",col.names = c(names(y), c("New_Col1", "New_Col2")),
colClasses = c(sapply(y, class), "character", "character"))
因此,在本例中,这两个新变量将获得character
类。我不知道y
如何限定为空数据帧。它有内容。你能详细说明一下你想在这里做什么吗?@TimBiegeleisen,很抱歉。我编辑了这个问题。@RonakShah。我想在y上增加两列。@RonakShah,是的。我添加了预期输出。这很有效。但是无论如何,我接下来要做的是rbind由lappy生成的data.frames(有些是空的)。这很重要。
> df2[1,] <- c(1, "hello", "world")
> df2
Ints Characters Stuff
1 1 hello world
df2$Ints <- c(1:5)
df2$Stuff <- c("one", "two", "three", "four", "five")
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)
read.table(text = "",col.names = c(names(y), c("New_Col1", "New_Col2")),
colClasses = c(sapply(y, class), "character", "character"))