transpose a dataframe according to a specific column in r

If you want to transpose a dataframe according to a specific column in R, you can use the tidyr package's gather and spread functions.

Here's an example code snippet that demonstrates how to do this:

main.r
library(tidyr)

# sample data
df <- data.frame(
  id = c(1, 1, 2, 2), 
  variable = c("var1", "var2", "var1", "var2"), 
  value = c(10, 20, 30, 40)
)

# transpose data
df_transposed <- df %>% 
  gather(key = "variable", value = "value", -id) %>% 
  spread(key = "variable", value = "value")

# show transposed data
df_transposed
329 chars
17 lines

In this example, the gather function is used to pivot the dataframe from wide to long format, with the variable column being used as the column to pivot on. Then, spread is used to pivot the dataframe back to wide format, with variable becoming the column names.

gistlibby LogSnag