如何将表格数据重塑为每组一行

编程入门 行业动态 更新时间:2024-10-27 23:18:00
本文介绍了如何将表格数据重塑为每组一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是一个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)

更多推荐

如何将表格数据重塑为每组一行

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

发布评论

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

>www.elefans.com

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