将数据添加到具有 0 行的 data.frame [英] Add data to data.frame with 0 rows
问题描述
考虑一下:
df <- data.frame(a=1:2, b=3:4)
我可以像这样添加一个新列并为其赋值:
df$c <- 5
但是如果我对它进行子集化,因此它是一个空的 data.frame 并尝试为其分配任何内容,它将返回一个错误:
df2 <- 子集(df, a==3)df2$d <- 10
<块引用>
$<-.data.frame(tmp, "d", value = 10) 中的错误:替换有 1 行,数据有 0
这将停止循环,所以我的问题是是否有其他方法可以为数据帧中的列赋值,而当数据帧为空时不会返回错误?
如果 OP 的目的是创建一个带有附加列的空 data.frame,您可以尝试:
df2$d <- 整数(0)df2#[1] a b c d#<0行>(或 0 长度的 row.names)
但是,这也可以在对 data.frame
的初始调用中完成:
data.frame(a = integer(0), b = integer(0), c = integer(0), d = integer(0))#[1] a b c d#<0行>(或 0 长度的 row.names)
Consider this:
df <- data.frame(a=1:2, b=3:4)
I can add a new column and assign values to it like this:
df$c <- 5
But if I subset this, so its an empty data.frame and try to assign anything to it, it will return an error:
df2 <- subset(df, a==3)
df2$d <- 10
Error in $<-.data.frame(tmp, "d", value = 10) : replacement has 1 row, data has 0
This will stop loops, so my question is if there are other ways to assign values to a column in a dataframe that does not return errors when the dataframe is empty?
If the intent of the OP is to create an empty data.frame with an additional column you may try:
df2$d <- integer(0)
df2
#[1] a b c d
#<0 rows> (or 0-length row.names)
However, this could have been done in the initial call to data.frame
as well:
data.frame(a = integer(0), b = integer(0), c = integer(0), d = integer(0))
#[1] a b c d
#<0 rows> (or 0-length row.names)
这篇关于将数据添加到具有 0 行的 data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!