将k列重塑为2个列,以表示k个变量的值的顺序对 [英] reshaping k columns to 2 columns representing sequential pairs of the values of the k variables

查看:92
本文介绍了将k列重塑为2个列,以表示k个变量的值的顺序对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

I have a data frame like this:

id y1 y2 y3 y4  
--+--+--+--+--
a |12|13|14|  
b |12|18|  |
c |13|  |  |
d |13|14|15|16  

我想重塑我以两列结尾。上面的示例将变为:

I want to reshape in such a way that I end with two columns. The above example would then become:

id from to  
--+----+--- 
a |12  |13  
a |13  |14  
a |14  |
b |12  |18
b |18  |  
c |13  |
d |13  |14  
d |14  |15  
d |15  |16  

每个 id 每对年份值都有一个'from'和'to'。

是否有人知道一种简单的方法这个?我尝试使用 reshape2 。我还查看了将多列合并为整齐数据,但我认为我的情况是不同。

Each id has a 'from' and a 'to' per pair of year values.
Does anybody know of an easy way to do this? I tried using reshape2. I also looked at Combine Multiple Columns Into Tidy Data but I think my case is different.

推荐答案

您可以使用 lapply 遍历各对列, rbind 进行合并:

You can use lapply to loop over the pairs of columns and rbind to union them:

do.call(rbind,
        lapply(2:(length(df)-1), 
               function(x) setNames(df[!is.na(df[,x]),c(1,x,x+1)], 
                                    c("id", "from", "to"))))
   id from to
1   a   12 13
2   b   12 18
3   c   13 NA
4   d   13 14
11  a   13 14
21  b   18 NA
41  d   14 15
12  a   14 NA
42  d   15 16

这篇关于将k列重塑为2个列,以表示k个变量的值的顺序对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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