How do I flip rows and columns in R

Assuming you have this data frame df, see data below.

  Country.Name 1997 1998 1999 2000
1     Country1    1    1    1    1
2     Country2    2    4    7   10
3     Country3    4    2    1    5

First you have to transpose all data frame except the first column. The result being a matrix that we need to convert to a data frame. Finally, we assign as column names of df2the first column of the original data frame df.

df2 <- data.frame(t(df[-1]))
colnames(df2) <- df[, 1]

Output:

     Country1 Country2 Country3
1997        1        2        4
1998        1        4        2
1999        1        7        1
2000        1       10        5

Data:

df <- structure(list(Country.Name = c("Country1", "Country2", "Country3"
), `1997` = c(1L, 2L, 4L), `1998` = c(1L, 4L, 2L), `1999` = c(1L, 
7L, 1L), `2000` = c(1L, 10L, 5L)), .Names = c("Country.Name", 
"1997", "1998", "1999", "2000"), class = "data.frame", row.names = c(NA, 
-3L))

Leave a Comment