Merging all the colunms in R with colunm names

后端 未结 3 919
北恋
北恋 2021-01-29 14:18

I have the following data

> df
X1  X2  X3 
1   3   4  
1   0   0  
1   1   0 

and I want to merge all the column so that the final output will

3条回答
  •  遥遥无期
    2021-01-29 14:56

    You can try gathering the column names with tidyr

    library(tidyr)
    
    X1 <- c(1,1,1)
    X2 <- c(3,0,1)
    X3 <- c(4,0,0)
    
    df <- data.frame(X1, X2, X3)
    
    df <- df %>%
      gather(new, colname, X1, X2, X3)
    
    print(df)
    
      new colname
    1  X1       1
    2  X1       1
    3  X1       1
    4  X2       3
    5  X2       0
    6  X2       1
    7  X3       4
    8  X3       0
    9  X3       0
    

提交回复
热议问题