在 R 中重塑数据将长表更改为宽表

编程入门 行业动态 更新时间:2024-10-28 18:23:29
本文介绍了在 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 中重塑数据将长表更改为宽表

本文发布于:2023-10-26 01:29:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528684.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   将长表更

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!