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
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.
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.
To change the row order in an R data frame, we can use single square brackets and provide the row order at first place.
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 df2
the 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With