在 data.frame 中将列切换到行 [英] Switch column to row in a data.frame

查看:42
本文介绍了在 data.frame 中将列切换到行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个 R 问题,这似乎有点棘手.我有一个如下所示的 data.frame:

I ran into an R problem, which seems to be a little bit tricky. I have a data.frame that looks like this:

Ident | A1 | ... | An | Z1 | ... | Zn
1     | 1  | ... | 1  | 1  | ... | 0
2     | 6  | ... | 4  | 0  | ... | 1
3     | 4  | ... | 4  | 1  | ... | 0
4     | 1  | ... | 4  | 0  | ... | 0

现在,我想要的是将原始 data.frame 转换为以下结构:

Now, what I want is to transform the original data.frame to the following structure:

Z     | A1 | ... | An
Z1    | 1  | ... | 1
Zn    | 6  | ... | 4
Z1    | 4  | ... | 4

如果任何行 Z 为 1,则仅将行纳入结果数据.

Only rows are taken into the resulting data if any of the rows Z's is 1.

有什么建议吗?一个起点可能就足够了.非常感谢.

Any suggestions? A starting point may be sufficient. Many thanks in advance.

这里是转储:

structure(list(Ident = c(1, 2, 3, 4), A1 = c(1, 6, 4, 1), A2 = c(1, 
4, 4, 4), Z1 = c(1, 0, 1, 0), Z2 = c(0, 1, 0, 0)), .Names = c("Ident", 
"A1", "A2", "Z1", "Z2"), row.names = c(NA, -4L), class = "data.frame")

推荐答案

假设 Ben 的答案是您正在寻找的(并使用他的示例数据),也许您可​​以使用 melt 和 <代码>合并,像这样:

Assuming that Ben's answer is what you're looking for (and using his sample data), perhaps you can use melt and merge, like this:

library(reshape2)
zCols <- grep("^Z", names(dat), value = TRUE)  ## Just the Z cols
otherCols <- setdiff(names(dat), zCols)        ## The other columns
datL <- melt(dat, measure.vars = zCols)        ## melting
merge(dat[otherCols],                          ## merging
      datL[as.logical(datL$value), c(otherCols, "variable")],
      all = TRUE)
#   Ident A1 A2 variable
# 1     1  1  1       Z1
# 2     2  6  4       Z2
# 3     3  4  4       Z1
# 4     4  1  4       Z1
# 5     5  2  3     <NA>

这篇关于在 data.frame 中将列切换到行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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