【问题标题】:How to add multiple empty columns to a data.frame with 0 rows?如何将多个空列添加到具有 0 行的 data.frame?
【发布时间】:2016-12-02 05:33:16
【问题描述】:

我可以在 data.frame 中添加列:

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

对于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

我找到了这个,Add Columns to an empty data frame in R,但没有多大帮助。

预期输出:

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

【问题讨论】:

  • 我看不出y 是如何成为一个空数据框的。它有内容。你能详细说明你在这里想要做什么吗?
  • @TimBiegeleisen,对此感到抱歉。我编辑了问题。
  • @RonakShah。我想向 y 添加 2 个新列。
  • @RonakShah,是的。我添加了预期的输出。

标签: r dataframe


【解决方案1】:

考虑以下创建空数据框的代码:

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

向这个空数据框添加新列的一种方法是使用cbind()

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

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

然后像往常一样添加您的数据,例如

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

正如您所提到的,这可能会导致Ints 列中的转换问题。单独分配每一列可以避免这种情况,例如

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

或者,您可以使用 read.table 之类的东西来引入您的数据,并以这种方式明确分配类。

【讨论】:

  • 这行得通。但是f2[1,] &lt;- c(1, "hello", "world") 将 Ints col 更改为字符!
  • 不管怎样,我接下来要做的是rbind lapply生成的data.frames(有些是空的)。这很重要。
【解决方案2】:

我们可以通过设置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)

我们也可以使用colClasses参数来设置我们想要的类

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

所以在这种情况下,两个新变量将获得character 类。

【讨论】:

    猜你喜欢
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2018-02-21
    • 2013-03-25
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多