r - 将观察不完整的行添加到 data.frame

标签 r dataframe

假设我有以下 data.frame :

    foo <- data.frame(ocean=c('Atlantic', 'Pacific'), 
        city=c('Boston', 'San Francisco'), 
        state=c('MA', 'CA'), stringsAsFactors=F)

我想添加第三行,但在这种情况下,只指定城市并将其他字段留空。

一些无效的幼稚方法包括:
foo$city[3] <- 'Providence'
# generates an error message about replacement has 3 rows, data has 2

这也会生成错误消息
rbind(foo, data.frame(city='Providence'))
# generates an error message, number of columns of arguments do not match

我对其他用户如何处理这个感兴趣。

最佳答案

另一种方法可能是使用 rbind.fillplyr包裹。

library(plyr)
bar <- data.frame(city="Providence", stringsAsFactors=F)
str(bar)

foobar <- rbind.fill(foo, bar)
str(foobar)

head(foobar)

关于r - 将观察不完整的行添加到 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5238753/

相关文章:

r - 如果列中出现负值,如何复制该列?

python - 在 pandas 列中搜索字符串

python - pandas dataframe聚合计算

r - 仅具有分类/逻辑的 GAM

r - 在 R 图表的基线中混合折线图和点

将信息分布在多个 View 中进行检索

斯卡拉 Spark : How to create a RDD from a list of string and convert to DataFrame

R H2o 对象未找到 H2OKeyNotFoundArgumentException

python - Pandas:合并两个数据框列

Python (2.7) - 考虑多个字段的简单 IF THEN 逻辑