How can I transpose my dataframe so that the rows and columns switch in r?

走远了吗. 提交于 2019-12-02 07:09:10

There are two ways you can do this. The first one is using t to just transpose the dataframe as if it would be a matrix (indeed the result of t is a matrix, not a dataframe).

The other option is to take the tidy data approach and use tidyr::spread along with tidyr::gather. Both have similar results although the second one is more versatile as it can be applied partially. Also notice that when using t the first column (which has type chr) will become the first row in the new matrix and therefore the entire matrix will be converted into a chr matrix, while gather+spread keeps the columns numeric.


library(tidyr)

df <- read.table(text = "Age Kodiak Banana Banff Montreal Fairfax
Age_1 5 6 7 9 2 
Age_2 7 6 4 3 2
Age_3 5 3 8 5 9", header = T)

t(df)
#>          [,1]    [,2]    [,3]   
#> Age      "Age_1" "Age_2" "Age_3"
#> Kodiak   "5"     "7"     "5"    
#> Banana   "6"     "6"     "3"    
#> Banff    "7"     "4"     "8"    
#> Montreal "9"     "3"     "5"    
#> Fairfax  "2"     "2"     "9"

df %>%
  gather("location", "value", 2:ncol(df)) %>%
  spread(Age, value)
#>   location Age_1 Age_2 Age_3
#> 1   Banana     6     6     3
#> 2    Banff     7     4     8
#> 3  Fairfax     2     2     9
#> 4   Kodiak     5     7     5
#> 5 Montreal     9     3     5

Use the t() function to transpose dataframes.

For example:

cars <- mtcars[1:5,1:4]
cars

                   mpg cyl disp  hp
Mazda RX4         21.0   6  160 110
Mazda RX4 Wag     21.0   6  160 110
Datsun 710        22.8   4  108  93
Hornet 4 Drive    21.4   6  258 110
Hornet Sportabout 18.7   8  360 175


t(cars)

     Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
mpg         21            21       22.8           21.4              18.7
cyl          6             6        4.0            6.0               8.0
disp       160           160      108.0          258.0             360.0
hp         110           110       93.0          110.0             175.0

source: https://www.r-statistics.com/tag/transpose/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!