Silva
Silva

Reputation: 73

R create a data.frame by adding lines, one each time

I'm trying to populate a data.frame (or something like it) line by line (one record each time).My problems:

  1. The data is not always present, and I don't want to lose the columns because they failed to have one instance of data. I want to set NA in this place.
  2. New columns can appear in the middle of process and others can be no more available.

What I'm trying to do is construct a data.frame with one row and insert vectors.

Example:

ddf <- data.frame("1", "2", "3", "4", stringsAsFactors = FALSE)
colnames(ddf) <- c("A","B","C","D")
View(ddf)
data_vector1 <- c("11","22","44")
names(data_vector1) <- c("A","B","D")
data_vector2 <- c("111","222","555")
names(data_vector2) <- c("A","B","E")

#What I want:
#     A    B    C    D     E  
#     1    2    3    4    NA
#    11   22   NA   44    NA
#   111  222   NA   NA   555

#Still now
samecols <- intersect(colnames(ddf),names(data_vector1))
ddf <- rbind(ddf, data_vector1[samecols])

#I'm getting:
#A  B  C  D
#1  2  3  4
#11 22 44 11

Upvotes: 3

Views: 225

Answers (1)

akrun
akrun

Reputation: 886948

We can place the datasets in a list, convert to data.frame and use rbindlist with fill=TRUE

library(data.table)
lst <- lapply(list(ddf, data_vector1, data_vector2), as.data.frame.list)
rbindlist(lst, fill=TRUE)
#     A   B  C  D   E
#1:   1   2  3  4  NA
#2:  11  22 NA 44  NA
#3: 111 222 NA NA 555

Or use bind_rows from dplyr

library(dplyr)
bind_rows(lst) 

Upvotes: 1

Related Questions