Passing column name to R tidyr distribution

I am trying to pass an object with a column name to a distribution function, but instead of reading the value inside the object, it just tries to use the name of the object itself

Here is just an example of a toy

library(tidyr) d = (1:4) n = c("a"," a", "b","b") s = c(1, 2,5,7) df = data.frame(d,n, s) Value <- n data_wide <- spread(df, Value , s) 

Error: there is no input in the "Value" column.

and below it works fine:

 data_wide <- spread(df, n, s) daab 1 1 NA 1 NA 2 2 2 NA NA 3 3 NA NA 5 4 4 NA NA 7 
+8
r tidy spread
source share
2 answers

We can use spread_() to pass variable names as strings:

 library(tidyr) # dummy data df1 <- data.frame(d = (1:4), n = c("a", "a", "b", "b") , s = c(1, 2, 5, 7)) myKey <- "n" myValue <- "s" spread_(data = df1, key_col = myKey , value_col = myValue) 
+12
source share

Using data.table

 library(data.table) dcast(setDT(df), eval(as.name(myValue))~ eval(as.name(myKey)), value.var=myValue) 

As for passing names in tidyr functions, this answer may also help (which was sent a couple of hours ago).

+3
source share

All Articles