简体   繁体   中英

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

I have a dataframe (simplified) that looks like this:

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

I would like my dataframe to look more like this:

Location, 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

I've looked at the transpose function but I'm a bit confused on how to switch both the columns and rows. I'm very new to R.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM