如何将两列“计数”矩阵转换为R中的二进制向量? [重复]

问题描述 投票:3回答:3

如何将具有两列计数矩阵的数据帧转换为R中具有单个二进制向量的数据帧?例如,我有一个这样的数据框,其中id是主题的id,s和f是该主题的“成功”和“失败”的数量,x是描述该主题的某些特征的第三个变量。

id s f x
1  0 3 A
2  2 1 A
3  1 2 B

我希望将此数据框转换为:

id n x
1  f A
1  f A
1  f A
2  s A
2  s A
2  f A
3  s B
3  f B
3  f B

其中列n表示每个试验是成功还是失败(f)。

我确定我可以编写一个函数来做这个,但我想知道是否有预制解决方案。

r reshape
3个回答
6
投票
  dd <- read.table(text="id s f x
    1  0 3 A
    2  2 1 A
    3  1 2 B",
    header=TRUE)

 with(dd,data.frame(
         id=rep(id,s+f),
         n=rep(rep(c("s","f"),nrow(dd)),c(rbind(s,f))),
         x=rep(x,s+f)))

5
投票

这是使用tidyrsplitstackshape包的一种方法。您使用gather重塑数据。然后,您可以在expandRows包中使用splitstackshape。您要求R按值列中的数字重复每一行。为了显示目的,我使用了arrange()包中的dplyr。但是,这部分是可选的。

library(tidyr)
library(splitstackshape)
library(dplyr)

gather(mydf, variable, value, -id, -x) %>%
expandRows("value") %>%
arrange(id, x)


#  id x variable
#1  1 A        f
#2  1 A        f
#3  1 A        f
#4  2 A        s
#5  2 A        s
#6  2 A        f
#7  3 B        s
#8  3 B        f
#9  3 B        f

3
投票

使用Ben Bolker上面的优秀答案,我创建了一个简短的函数,它将对包含一列成功计数,一列失败计数以及包含每行(主题)信息的任意数量的其他列的任何数据框执行此操作。见下面的例子。

#####################################################################
### cnt2bin (count to binary) takes a data frame with 2-column ######
### "count" response variable of successes and failures and    ######
### converts it to long format, with one column showing        ######
### 0s and 1s for failures and successes.                      ######
### data is data frame with 2-column response variable         ######
### suc and fail are character expressions for columns         ######
### containing counts of successes and failures respectively   ######
#####################################################################

cnt2bin <- function(data, suc, fail) {

  xvars <- names(data)[names(data)!=suc & names(data)!=fail]
  list <- lapply(xvars, function(z) with(data, rep(get(z), get(suc)+get(fail))))
  names(list) <- xvars
  df <- as.data.frame(list)
  with(data,data.frame(bin=rep(rep(c(1,0),nrow(data)),c(rbind(get(suc),get(fail)))),
                       df))
}

例如,id是主题id,s和f是计算每个主题的成功和失败的列,x和y是描述每个主题的属性的变量,要扩展并添加到最终数据框。

dd <- read.table(text="id s f x y
                       1  0 3 A A
                       2  2 1 A B
                       3  1 2 B B",
                  header=TRUE)

cnt2bin(dd, "s", "f")
© www.soinside.com 2019 - 2024. All rights reserved.