Add data to data.frame with 0 rows

。_饼干妹妹 提交于 2020-01-07 05:16:23

问题


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?


回答1:


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)



回答2:


You can achieve this in one line with dplyr by subsetting the data.frame with filter and then adding a new column with mutate. It won't crash whether your subsetting operation (filter here) results in an empty data.frame or not:

library(dplyr)
df <- data.frame(a=1:2, b=3:4)
df2 <- df %>% filter(a==3) %>% mutate(d=10)
# [1] a b d
# <0 rows> (or 0-length row.names)


来源:https://stackoverflow.com/questions/42341286/add-data-to-data-frame-with-0-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!