transpose - transposing rows into multiple columns in R -
i have following data frame df
id year var value 1 2011 x1 1.2 1 2011 x2 2 1 2012 x1 1.5 1 2012 x2 2.3 3 2013 x1 3 3 2014 x1 4 4 2015 x1 5 5 2016 x1 6 4 2016 x1 2
i want transform data in following format
id year x1 x2 1 2011 1.2 2 1 2011 2 na 1 2012 1.5 2.3 3 2013 3 na 3 2014 4 4 4 2015 5 na 4 2016 2 na 5 2016 6 na
please help
using tidyr
library, believe looking for:
df <- data.frame(stringsasfactors=false, id = c(1l, 1l, 1l, 1l, 3l, 3l, 4l, 5l, 4l), year = c(2011l, 2011l, 2012l, 2012l, 2013l, 2014l, 2015l, 2016l, 2016l), var = c("x1", "x2", "x1", "x2", "x1", "x1", "x1", "x1", "x1"), value = c(1.2, 2, 1.5, 2.3, 3, 4, 5, 6, 2) ) library(tidyr) df2 <- df %>% spread(var, value)
Comments
Post a Comment