在 R 中重塑数据将长表更改为宽表 [英] Reshape data in R change a long table into a wide table

查看:63
本文介绍了在 R 中重塑数据将长表更改为宽表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 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 中重塑数据将长表更改为宽表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆