Reshaping data.frame with a by-group where id variable repeats [duplicate]

蹲街弑〆低调 提交于 2020-06-09 05:37:25

问题


I want to reshape/ rearrange a dataset, that is stored as a data.frame with 2 columns:

  • id (non-unique, i.e. can repeat over several rows) --> stored as character
  • value --> stored as numeric value (range 1:3)

Sample data:

id <- as.character(1001:1003)
val_list <- data.frame(sample(1:3, size=12, replace=TRUE))
have <- data.frame(cbind(rep(id, 4), val_list))
colnames(have) <- c("id", "values")
have <- have %>% arrange(id)

This gives me the following output:

   id   values
1  1001      2
2  1001      2
3  1001      2
4  1001      3
5  1002      2
6  1002      3
7  1002      2
8  1002      2
9  1003      1
10 1003      3
11 1003      1
12 1003      2

What I want:

want <- data.frame(cbind(have[1:4, 2], 
                     have[5:8, 2],
                     have[9:12, 2]))
colnames(want) <- id

Output of want:

    1001 1002 1003
  1    2    2    1
  2    2    3    3
  3    2    2    1
  4    3    2    2

My original dataset has >1000 variables "id" and >50 variables "value". I want to chunk/ slice the dataset get a new data.frame where each "id" variable will represent one column listing its "value" variable content.

It is possible to solve it via a loop, but I want to have the vectorized solution. If possible with base R as "one-liner", but other solutions also appreciated.


回答1:


You can create a unique row value for each id and use pivot_wider.

have %>%
  group_by(id) %>%
  mutate(row = row_number()) %>%
  tidyr::pivot_wider(names_from = id, values_from = values) %>%
  select(-row)

# A tibble: 4 x 3
#  `1001` `1002` `1003`
#   <int>  <int>  <int>
#1      1      3      1
#2      3      2      3
#3      2      2      3
#4      2      2      3

Or using data.table

library(data.table)
dcast(setDT(have), rowid(id)~id, value.var = 'values')

data

df <- structure(list(id = c(1001L, 1001L, 1001L, 1001L, 1002L, 1002L, 
1002L, 1002L, 1003L, 1003L, 1003L, 1003L), values = c(2L, 2L, 
2L, 3L, 2L, 3L, 2L, 2L, 1L, 3L, 1L, 2L)), class = "data.frame", 
row.names = c(NA, -12L))


来源:https://stackoverflow.com/questions/61867904/reshaping-data-frame-with-a-by-group-where-id-variable-repeats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!