4

I'm trying to learn how to use tidyr to transfor wide data to long. Suppose my data looks like this:

df1 <- data.frame(V1=c(1.5,7.4), 
                  V2=c(6.7,8.8),
                  sim=c(1,2))

I want to transform me to look like this:

df2 <- data.frame(sim=c(1,1,2,2),
                  Value=c(1.5,6.7,7.4,8.8))

I think gather is the function that I have to use, but I'm not understanding the help file. This is what I have right now:

df1 %>%
   gather(key=sim, value=V1:V2)

The error says "Error: Invalid column specification"

Thanks!

Ignacio
  • 7,646
  • 16
  • 60
  • 113

1 Answers1

4

Try

library(tidyr)
df1 %>%
    gather(sim1, Value, V1:V2) %>% 
    select(-sim1) %>%
    arrange(sim)
#    sim Value
#1   1   1.5
#2   1   6.7
#3   2   7.4
#4   2   8.8

According to ?gather

  gather(data, key, value, ..., na.rm = FALSE, convert = FALSE)

key,value: Names of key and value columns to create in output.

...: Specification of columns to gather. Use bare variable names. Select all variables between x and z with ‘x:z’, exclude y with ‘-y’. For more options, see the select documentation.

akrun
  • 874,273
  • 37
  • 540
  • 662