[R] Use gather with a various number of columns

ruipb@rr@d@s m@iii@g oii s@po@pt ruipb@rr@d@s m@iii@g oii s@po@pt
Wed Aug 28 09:03:20 CEST 2019


Just don't include the names of those columns.
Is this what you want?


df_initial1 <- 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_initial2 <- data.frame(col1name=c(1,2,3,4,5,6,7),  
df_initial3 <- 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),  

gather(df_initial1, key="colall", value="value")
gather(df_initial2, key="colall", value="value")
gather(df_initial3, key="colall", value="value")

Hope this helps,

Rui Barradas

Citando lionel sicot via R-help <r-help using r-project.org>:

> 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]]
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list