将数据添加到具有 0 行的 data.frame [英] Add data to data.frame with 0 rows

查看:29
本文介绍了将数据添加到具有 0 行的 data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆