假设我有以下 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.fill
在 plyr
包裹。
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/