我想用 R 中的 reshape2 包把我的长表改成宽表.
I would like to use the reshape2 package in R to change my long table into a wide table.
我有一个来自数据库的数据集,就像这样(示例):
I have a data set from database which is like this (example):
id1 | id2 | info | action_time | 1 | a | info1 | time1 | 1 | a | info1 | time2 | 1 | a | info1 | time3 | 2 | b | info2 | time4 | 2 | b | info2 | time5 |现在我希望它是这样的:
And now I want it to be like this:
id1 | id2 | info |action_time 1|action_time 2|action_time 3| 1 | a | info1 | time1 | time2 | time3 | 2 | b | info2 | time4 | time5 | |我尝试了几次,并使用 reshape() 或 dcast() 在某些网站上查找了一些示例,但找不到这样的示例.每个 id 的 action_time 数量是不同的,并且对于某些 id,它们可能有 10 个以上的 action_time,因此在这种情况下,重构的数据集将有 10 个以上action_time 列.
I have tried several times and looked up some examples on some website using reshape() or dcast() but couldn't find such example like this. The number of action_time for each id is different and for some of the ids they may have more than 10 action_times so in that case the reshaped data set will have more than 10 columns of action_time.
谁能想到一个方便的方法来做到这一点?如果有一种方法可以在 excel(数据透视表?)中做到这一点,那也太棒了.感谢堆
Anyone can think of a handy way of doing this? If there is a way of doing this in excel(Pivot Table?) it would be awesome as well. Thank heaps
推荐答案尝试:
library(dplyr) library(tidyr) df %>% group_by(id1) %>% mutate(action_no = paste("action_time", row_number())) %>% spread(action_no, action_time)给出:
#Source: local data frame [2 x 6] # # id1 id2 info action_time 1 action_time 2 action_time 3 #1 1 a info1 time1 time2 time3 #2 2 b info2 time4 time5 NA数据
df <- structure(list(id1 = c(1, 1, 1, 2, 2), id2 = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("a", "b"), class = "factor"), info = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("info1", "info2"), class = "factor"), action_time = structure(1:5, .Label = c("time1", "time2", "time3", "time4", "time5"), class = "factor")), .Names = c("id1", "id2", "info", "action_time"), class = "data.frame", row.names = c(NA, -5L))更多推荐
在 R 中重塑数据将长表更改为宽表
发布评论