change data.frame column into rows in R

前端 未结 2 1037
遇见更好的自我
遇见更好的自我 2020-12-29 05:08
A <- c(1,6)
B <- c(2,7)
C <- c(3,8)
D <- c(4,9)
E <- c(5,0)
df <- data.frame(A,B,C,D,E)
df
  A B C D E
1 1 2 3 4 5
2 6 7 8 9 0

I

2条回答
  •  旧时难觅i
    2020-12-29 05:30

    If your dataframe is truly in that format, then all of your vectors will be character vectors. Or, you basically have a character matrix and you could do this:

    data.frame(t(df))
    

    It would be better, though, to just define it the way you want it from the get-go

    df <- data.frame(c('A','B','C','D','E'), 
                     c(1, 2, 3, 4, 5),
                     c(6, 7, 8, 9, 0))
    

    You could also do this

    df <- data.frame(LETTERS[1:5], 1:5, c(6:9, 0))
    

    If you wanted to give the columns names, you could do this

    df <- data.frame(L = LETTERS[1:5], N1 = 1:5, N2 = c(6:9, 0))
    

    Sometimes, if I use read.DIF of Excel data the data gets transposed. Is that how you got the original data in? If so, you can call

    read.DIF(filename, transpose = T)
    

    to get the data in the correct orientation.

提交回复
热议问题