Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fill missing columns with NA while extracting from a data.frame

Tags:

dataframe

r

I have a function that takes as input a dataframe with certain columns

columns =['a', 'b',...,'z']

Now I have a dataframe DF with only few of these columns DF_columns = ['f', 'u', 'z']

How can I create a dataframe that has all the columns with value NA if the columns are not in DF and that coincides with DF on the columns ['f', 'u', 'z']

Example:

d = data.frame('g'=c(1,2,3), 's' = c(4,2,3))
columns = letters[1:21]
columns
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t"
[21] "u"

> d
  g s
1 1 4
2 2 2
3 3 3
> 
like image 333
Donbeo Avatar asked Feb 03 '26 05:02

Donbeo


1 Answers

x.or.na <- function(x, df) if (x %in% names(df)) df[[x]] else NA
as.data.frame(Map(x.or.na, columns, list(d)))
like image 58
flodel Avatar answered Feb 05 '26 21:02

flodel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!