【问题标题】:Dividing by all combinations of a variable grouped by factor in R除以 R 中按因子分组的变量的所有组合
【发布时间】:2019-10-25 01:03:07
【问题描述】:

我的数据如下所示:

set <- rep(c(1,2,3,4), each = 15)
h_density <- rep(c(1,3,6), each =5 )
n_density <- rep(c(100,500,1000,5000,10000), times =4 )
counts <- runif(60,900,10000)
data <- data.frame(set,h_density,n_density,counts)
data$set <- as.factor(data$set)
data$n_density <- as.factor(data$n_density)
data$h_density <- as.factor(data$h_density)

在给定的集合中,有三个级别的h_densities 1、3、6 和五个级别的n_densities 100,500,1000,5000,1000。对于给定的集合和给定的h_density,我想将低密度的counts 的所有可能组合划分为高密度。所以,我想划分与 n_densities 100/500, 100/1000, 100/5000, 100/10000, 500/1000, 500/5000, 500/10000, 1000/5000, 1000/10000, 5000/10000 相关的计数。对于输出,我想打印集合,h_density,n_densities 的打印比率,n_densities 的比率计数

例如,前几行的结果应如下所示:

 set h_density n_density_ratio count_ratio
  1   1        100/500         <value>          
  1   1        100/1000        <value>    
  1   1        100/5000        <value>    
  1   1        100/10000       <value>      
  1   1        500/1000        <value>      
  1   1        500/5000        <value>     
 ...

如何在 R 中实现这一点?

【问题讨论】:

    标签: r loops dplyr combinations division


    【解决方案1】:

    如果您的数据不是太大,通过inner_join() 进行所有组合并通过n_density 的不等式过滤它是很好且简单的。

    library(dplyr)
    
    data %>% 
      inner_join(data, by = c("set", "h_density"), suffix = c(".l", ".r")) %>% 
      filter(as.numeric(n_density.l) < as.numeric(n_density.r)) %>% 
      mutate(n_density_ratio = paste0(n_density.l , "/", n_density.r)) 
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 2020-05-25
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 2018-11-27
      相关资源
      最近更新 更多