I have a vector of column names (262 of them) and a data frame with the same column names, but missing several of the columns (so rather than 262 columns, I have 250 columns).
Is there a way to set the columns of the data frame to the vector containing the complete set of column names, and for the names which there is no data for - generate a column of NAs?
For example, if I have a vector and data frame that looks like:
column_names <- c("col1","col2","col3","col4","col5","col6","col7")
df1 <- data.frame(c(20,30,10,20,45),c(1,10,2,45,2),c(9,10,22,11,12),c(87,7,7,7,14),c(89,90,99,12,1))
names(df1) <-c("col1","col2","col3","col5","col6")
# col1 col2 col3 col5 col6
# 20 1 9 87 89
# 30 10 10 7 90
# 10 2 22 7 99
# 20 45 11 7 12
# 45 2 12 14 1
I'd like to generate one that looks like:
df2 <- data.frame(c(20,30,10,20,45),c(1,10,2,45,2),c(9,10,22,11,12),c("NA","NA","NA","NA","NA"),c(87,7,7,7,14),c(89,90,99,12,1),c("NA","NA","NA","NA","NA"))
names(df2) <-column_names
# col1 col2 col3 col4 col5 col6 col7
# 20 1 9 NA 87 89 NA
# 30 10 10 NA 7 90 NA
# 10 2 22 NA 7 99 NA
# 20 45 11 NA 7 12 NA
# 45 2 12 NA 14 1 NA