简体   繁体   中英

How to transpose/reshape this dataframe

How is it possible to transform the dataframe to achieve the desired outcome?

Here is a sample dataframe:

id <- c("Item1","Item2","Item3","Item1","Item2","Item3")
year <- c(2016,2016,2016,2017,2017,2017)
WSP1 <- c(1:6)
WSP2 <- c(7:12)
test <- data.frame(id, year, WSP1, WSP2)

Desired output:

WSP |year |Item1 |Item2 |Item3
WSP1|2016 |1     |2     |3
WSP1|2017 |4     |5     |6
WSP2|2016 |7     |8     |9
WSP2|2017 |10    |11    |12

I've tried:

test1 <- pivot_longer(test,-year)
test2 <- pivot_wider(test,-year)

You can try the following:

library(tidyr)

test %>% 
  pivot_longer(cols = c(WSP1, WSP2), names_to = "WSP") %>%
  pivot_wider(names_from = "id")

# A tibble: 4 x 5
#    year WSP   Item1 Item2 Item3
#   <dbl> <chr> <int> <int> <int>
# 1  2016 WSP1      1     2     3
# 2  2016 WSP2      7     8     9
# 3  2017 WSP1      4     5     6
# 4  2017 WSP2     10    11    12

You can try this. I hope this helps:

library(reshape2)
df0 <- melt(test,id.vars = c('id','year'))
#Reshape
df1 <- reshape(data = df0,idvar = c('variable','year'),timevar = 'id',direction = 'wide')

   year variable value.Item1 value.Item2 value.Item3
1  2016     WSP1           1           2           3
4  2017     WSP1           4           5           6
7  2016     WSP2           7           8           9
10 2017     WSP2          10          11          12

An option with recast from reshape2

library(reshape2)
recast(test, id.var = c('id', 'year'), variable + year ~ id)
# variable year Item1 Item2 Item3
#1     WSP1 2016     1     2     3
#2     WSP1 2017     4     5     6
#3     WSP2 2016     7     8     9
#4     WSP2 2017    10    11    12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM