繁体   English   中英

在data.frame中将列切换为行

[英]Switch column to row in a data.frame

我遇到了R问题,这似乎有些棘手。 我有一个data.frame看起来像这样:

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转换为以下结构:

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

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

有什么建议么? 起点可能就足够了。 提前谢谢了。

这里是转储:

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")

你可以写类似

dframe<-dframe[sum(dframe[,zindex1:zindexN])>0,Aindex1:AindexN]

其中zindex1:zindexN是Z的列索引范围,而Aindex类似。

设置数据:

编辑 :添加全零行。

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

找出哪些列具有Z元素:

Zcols <- grep("^Z[0-9]+",names(dat))

拔出他们的名字:

Znames <- names(dat)[Zcols]

确定相关列并获取适当的名称:

w <- apply(dat[Zcols],1,
           function(x) if (all(x==0)) NA else which(x==1))
dd <- data.frame(Z=Znames[w], dat[-Zcols])

如果您愿意,可以转换NA值:

levels(dd$Z) <- c(levels(dd$Z),"missing")
dd$Z[is.na(dd$Z)] <- "missing"

##         Z Ident A1 A2
## 1      Z1     1  1  1
## 2      Z2     2  6  4
## 3      Z1     3  4  4
## 4      Z1     4  1  4
## 5 missing     5  2  3

假设Ben的答案就是您想要的(并使用他的样本数据),也许您可​​以使用melt and merge ,如下所示:

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM