0

I have the following products list

> products
# A tibble: 311 x 1
   value                    
   <fct>                    
 1 NA                       
 2 Alternativ Economy
 3 Ambulant Balance  
 4 Ambulant Economy  
 5 Ambulant Premium  
 6 Ambulant 2               
 7 Ambulant 3               
 8 Ambulant 1               
 9 COMPLETA                 
10 HOSPITAL ECO             
# ... with 301 more rows

and the following df

> df <- data.frame(employee = c('John Doe','Peter Gynn','Jolie Hope'), 
+           salary = c(21000, 23400, 26800), 
+           startdate = as.Date(c('2010-11-1','2008-3-25','2007-3-14')))
> df
    employee salary  startdate
1   John Doe  21000 2010-11-01
2 Peter Gynn  23400 2008-03-25
3 Jolie Hope  26800 2007-03-14

Now, I want to add the elements of the former (i.e. products) as variables of the latter (i.e. the df). I use

cbind(df, setNames(lapply(products, function(x) x = NA), products))

but I get an error. Can you suggest another way of doing this? What is wrong with my solution? thanks in advance

daniell
  • 169
  • 1
  • 9

1 Answers1

0

Here is one solution.

df <- data.frame(employee = c('John Doe','Peter Gynn','Jolie Hope'), 
                 salary = c(21000, 23400, 26800), 
                 startdate = as.Date(c('2010-11-1','2008-3-25','2007-3-14')))

products <- data.frame(value = c(NA, "Alternativ Economy", "COMPLETA"))
#products$value <- ifelse(is.na(products$value), "not_available", as.character(products$value))

cbind(df, `colnames<-`(data.frame(matrix(ncol = nrow(products), nrow = nrow(df))), products$value))

    employee salary  startdate NA Alternativ Economy COMPLETA
1   John Doe  21000 2010-11-01 NA                 NA       NA
2 Peter Gynn  23400 2008-03-25 NA                 NA       NA
3 Jolie Hope  26800 2007-03-14 NA                 NA       NA

I question the wisdom of having NAs as column names, so I'd uncomment that one line of code in there to replace NAs with some character string instead.

Dunois
  • 1,813
  • 9
  • 22