Raidho
Raidho

Reputation: 105

Use of gather() in a loop, "key" and "value" as a variable

I like to use gather() in loop, where values for the inputs of gather() key and value are a variable. Is this possible?

I also tried gather() with a standard variable (set outside the loop, without a index), but is doesn't work.

So, I assume, that it is not possible per definition of _gather()_to assign key and value to a variable.

In the documentation I found on key and value:

"...note that this kind of interface where symbols do not represent actual objects..."

I assume that's the answer. But I'm not sure.

gather(Fragenummern.FB[i], Fragenummern.FI[i], 
       key = keyVar[i], value = ValueVar[i])  

Error: Must supply a symbol or a string as argument

Call rlang::last_error() to see a backtrace

Upvotes: 1

Views: 601

Answers (1)

kstew
kstew

Reputation: 1114

I think you can achieve this using dplyr::gather and rlang commands. In this example, you have your df, a vector of some variable names in df that you want to gather, and a vector of names for the newly gathered variables.

df <- data.frame(matrix(runif(260),ncol = 26))
names(df) <- letters

to_gather <- sample(letters,5)
new_names <- c('letter','value')

df %>% gather(key = !!new_names[1], value = !!new_names[2], enexpr(to_gather))

And you can loop over this and create multiple new data frames based on different subsets of variables to gather.

lapply(1:2, function(x){
  to_gather <- sample(letters,5)
  df %>% gather(key = !!new_names[1], value = !!new_names[2], enexpr(to_gather))
  })

Upvotes: 2

Related Questions