[R] Use gather with a various number of columns

lionel sicot pt|t_b|eu @end|ng |rom y@hoo@|r
Wed Aug 28 08:20:38 CEST 2019


Hello,
I'm using the gather function from the tidyr package to reshape data.frames.
For example, for the the following dataframe, I apply the command below.df_initial<-data.frame(col1name=c(1,2,3,4,5,6,7), col2name=c(4,5,6,7,8,9,1), col3name=c(9,8,7,6,5,4,3))df_reshaped<-gather(df_initial, "col1name", "col2name", "col3name", key="colall", value="value")

In this example, there are 3 columns because there were 3 devices. But the number of devices can change and I would like to avoid adding new columns by hand in the 'gather' command.
Is there a way to adapt the command so that it automatically detect the number of columns of df_initial :

df_initial<-data.frame(col1name=c(1,2,3,4,5,6,7), col2name=c(4,5,6,7,8,9,1), col3name=c(9,8,7,6,5,4,3))
df_initial<-data.frame(col1name=c(1,2,3,4,5,6,7), col2name=c(4,5,6,7,8,9,1))
df_initial<-data.frame(col1name=c(1,2,3,4,5,6,7), col2name=c(4,5,6,7,8,9,1), col3name=c(9,8,7,6,5,4,3), col4name=c(5,6,8,9,7,4,1))
df_reshaped_auto<-gather(df_initial, ?????????, key="colall", value="value")

Thanks in advance to help me replace ?????????,Ptit Bleu.

	[[alternative HTML version deleted]]



More information about the R-help mailing list