2019-01-16

How do I transpose a data frame in R?

Problem

We need to transpose a data frame.

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)
  )
  Country.Name 1997 1998 1999 2000
1     Country1    1    1    1    1
2     Country2    2    4    7   10
3     Country3    4    2    1    5

Solution

The t function will return the transpose of a matrix or data frame.

# Transpose all but the firs column
df_transpose <- data.frame(t(df[-1]))
# Add column names
colnames(df_transpose) <- df[, 1]
df_transpose
     Country1 Country2 Country3
1997        1        2        4
1998        1        4        2
1999        1        7        1
2000        1       10        5

Related posts

References

No hay comentarios:

Publicar un comentario

Nube de datos