Reputation: 3035
Suppose I have the following 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.
Upvotes: 4
Views: 4688
Reputation: 7551
foo[3,] <- NA
foo$city[3] <- 'Providence'
OR
foo[3,] <- c(NA,'Providence',NA)
Upvotes: 3
Reputation: 40126
Another approach might be to use rbind.fill
in the plyr
package.
library(plyr)
bar <- data.frame(city="Providence", stringsAsFactors=F)
str(bar)
foobar <- rbind.fill(foo, bar)
str(foobar)
head(foobar)
Upvotes: 3