Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I flip rows and columns in R

Tags:

r

I currently have:

Country.Name   1995 1996 1997 ... 2013
Country1       
Country2        (numeric data)
Country3

-This format makes it difficult to graph the data for each country, and compare them, since the header columns are individual years

I want:

Year  Country1   Country2   Country3
1995
1996        
1997           (numeric data)
...
2013
like image 615
lr1116 Avatar asked Nov 11 '15 02:11

lr1116


People also ask

How do I flip a column and a row in R?

Rotating or transposing R objects You can rotate the data. frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.

How do I reverse the order of rows in R?

The rev() method in R is used to return the reversed order of the R object, be it dataframe or a vector. It computes the reverse columns by default. The resultant dataframe returns the last column first followed by the previous columns. The ordering of the rows remains unmodified.

How do I switch rows in R?

To change the row order in an R data frame, we can use single square brackets and provide the row order at first place.


1 Answers

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))
like image 159
mpalanco Avatar answered Oct 21 '22 06:10

mpalanco