【问题标题】:Is it possible to ask R randomly pick two variables from a group of binary variables to calculate the proportion?是否可以要求 R 从一组二元变量中随机选择两个变量来计算比例?
【发布时间】:2020-03-10 02:09:48
【问题描述】:

我在数据集中有几个二进制变量,我想计算两个变量的所有组合中“1 1”的比例。例如(a1=1 和 a2=1)的比例。我可以每次手动指定两个变量来运行代码,但是我的数据中有超过 10 个变量,因此至少会有 45 个组合。有没有办法让 R 自动配对变量为我计算?

structure(list(a1 = structure(c(2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L), 
                              .Label = c("0", "1"), class = "factor"), 
               a2 = structure(c(1L,1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L), 
                              .Label = c("0", "1"), class = "factor"),
               a3 = structure(c(1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L,1L, 1L), 
                              .Label = c("0", "1"), class = "factor"), 
               a4 = structure(c(1L,2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), 
                              .Label = c("0","1"), class = "factor"), 
               a5 = structure(c(2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L), 
                              .Label = c("0", "1"), class = "factor")), row.names = 180:190, class = "data.frame")

【问题讨论】:

  • @arkun 我修改了那个。

标签: r


【解决方案1】:

我们可以创建一个函数来获取sample的列名选择两个,然后对数据进行子集化,检查两个列是否等于1,得到mean

f1 <- function(dat) {
    nm1 <- sample(names(dat), 2, replace = FALSE)
    setNames(mean(dat[,nm1[1]]== 1 & dat[,nm1[2]] == 1), paste(nm1, collapse="_"))
   }

f1(df1)
# a3_a5 
#   0 

如果我们想要所有的组合

f1 <- function(dat) {
       combn(names(dat), 2, FUN = function(nm) {
              nm1 <- paste(nm, collapse="_")
              setNames(mean(dat[, nm[1]] ==1 & dat[, nm[2]] == 1), nm1)},
  simplify = FALSE) 
   }

f1(df1)
#[[1]]
#a1_a2 
#    0 

#[[2]]
#a1_a3 
#    0 

#[[3]]
#a1_a4 
#    0 

#[[4]]
#     a1_a5 
#0.09090909 

#[[5]]
#     a2_a3 
#0.09090909 

#[[6]]
#a2_a4 
#    0 

#[[7]]
#     a2_a5 
#0.09090909 

#[[8]]
#a3_a4 
#    0 

#[[9]]
#a3_a5 
#    0 

#[[10]]
#a4_a5 
#    0 

【讨论】:

  • 它有一个错误说 Error in dat[, x[1]] : wrong number of dimensions.
  • 谢谢!对不起,我没有把我的问题说清楚。我想计算所有可能组合的平均值。 (这个函数在每次随机选择两个来计算比例方面做得很好,但我需要反复运行它,不确定是否能得到所有组合的结果)
  • @user12721567 ii 虽然你想a way to ask R randomly pair up the variables to calculate for me
  • 是的。并且每次运行该函数,都会产生一个结果。因为它是随机选择这对变量,比如说如果我有 10 个变量,那么可以有 45 个组合。即使每次生成的组合不同,我也需要运行代码 45 次才能获得所需的完整结果,rt?
  • @user12721567 这就是我之前有combn 的原因,但后来因为随机配对而改变了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
相关资源
最近更新 更多