简体   繁体   English

将具有不完整观察的行添加到data.frame

[英]Adding a row with incomplete observations to a data.frame

Suppose I have the following data.frame : 假设我有以下data.frame

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

I would like to add a third row, but in this case, only specify the city and leave the other fields blank. 我想添加第三行,但在这种情况下,只指定城市并将其他字段留空。

Some naive ways, which do not work include: 一些天真的方法,不起作用包括:

foo$city[3] <- 'Providence'
# generates an error message about replacement has 3 rows, data has 2

This also generates an error message 这也会生成错误消息

rbind(foo, data.frame(city='Providence'))
# generates an error message, number of columns of arguments do not match

I'm interested in how other users would approach this. 我对其他用户如何处理这个问题很感兴趣。

foo[3,] <- NA
foo$city[3] <- 'Providence'

OR 要么

foo[3,] <- c(NA,'Providence',NA)

Another approach might be to use rbind.fill in the plyr package. 另一种方法可能是在plyr包中使用rbind.fill

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

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

head(foobar)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM