Binding columns with similar column names in the same dataframe in R

后端 未结 5 1202
挽巷
挽巷 2021-01-05 06:01

I have a data frame that looks somewhat like this:

df <- data.frame(0:2, 1:3, 2:4, 5:7, 6:8, 2:4, 0:2, 1:3, 2:4)
colnames(df) <- rep(c(\'a\', \'b\', \         


        
5条回答
  •  长情又很酷
    2021-01-05 06:22

    I would sort the data.frame by column name, unlist, and use as.data.frame on a matrix:

    A <- unique(names(df))[order(unique(names(df)))]
    B <- matrix(unlist(df[, order(names(df))], use.names=FALSE), ncol = length(A))
    B <- setNames(as.data.frame(B), A)
    B
    #   a b c
    # 1 0 1 2
    # 2 1 2 3
    # 3 2 3 4
    # 4 5 6 2
    # 5 6 7 3
    # 6 7 8 4
    # 7 0 1 2
    # 8 1 2 3
    # 9 2 3 4
    

提交回复
热议问题