如何将表格数据重塑为每组一行 [英] How to reshape tabular data to one row per group

查看:16
本文介绍了如何将表格数据重塑为每组一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个R(和编程新手),我正在寻找一种方法将下面的表A显示重新配置为表B。

表A:

type   x1  x2  x3  
A      4   6   9  
A      7   4   1  
A      9   6   2   
B      1   3   8  
B      2   7   9

我正在寻找可以转换为以下内容的代码

表B:

type   x1  x2  x3  x1'  x2'  x3'  x1'' x2'' x3''  
A      4    6   9   7    4   1    9     6   2  
B      1    3   8   2    7   9   

实际的表A有150000多行36列。具有2100个唯一的"类型"值。

谢谢您的帮助。

-Shawn

推荐答案

在我看来,此解决方案非常简单

# split the data frame by type and use unlist, which will provide names
ld <- lapply(split(d[-1], d[["type"]]), unlist)

# gather all the unique names in the list
ldNames <- Reduce(unique, lapply(ld, names))

# use the names to index each list element, which makes them
# all of equal length and suitable for row binding.  
do.call(rbind, lapply(ld, function(x) x[ldNames]))
#   x11 x12 x13 x21 x22 x23 x31 x32 x33
# A   4   7   9   6   4   6   9   1   2
# B   1   2  NA   3   7  NA   8   9  NA

如果以上输出的顺序不令人满意,您可以重新排列:

# save the output from above
d2 <- do.call(rbind, lapply(ld, function(x) x[ldNames]))
# reorder the names
ldNames_sorted <- c(matrix(ldNames, ncol = (ncol(d) - 1), byrow = TRUE))

# apply the new order.
d2 <- d2[, ldNames_sorted]
#  x11 x21 x31 x12 x22 x32 x13 x23 x33
#A   4   6   9   7   4   1   9   6   2
#B   1   3   8   2   7   9  NA  NA  NA

若要为类型添加列而不使用行名,一种方法是:

data.frame(type = row.names(d2), d2)

这篇关于如何将表格数据重塑为每组一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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