除以R中按因子分组的变量的所有组合

Dividing by all combinations of a variable grouped by factor in R

我的数据是这样的:

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 中实现这一点?

如果您的数据不是太大,通过 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))