繁体   English   中英

使用 rowsum 或 rowSums 进行子集化

[英]Subsetting using rowsum or rowSums

我对 R 很陌生。 我想创建一个包含 4 种材料的配方的所有可能浓度组合的列表。 最后一行是我遇到问题的地方。

#create a sequence of numbers from 0.01 to 0.97 by 0.01
#(all possible concentration combinations for a recipe of 4 unique materials)
concs<-seq(0.01,0.97,0.01)

#create all possible permutations of these numbers with repeats
combos2<-permutations(length(concs),4,concs,TRUE,TRUE)

#subset the list of possible concentrations so that all that is left are the rows of data
#where all four values (4 columns) in a row (the four material concentrations) sum to 1
combos2<-combos2[rowSums(combos2[,1:4])==1]

如何创建一个子集向量,例如:

#create a sequence of numbers from 0.01 to 0.97 by 0.01
#(all possible concentration combinations for a recipe of 4 unique materials)
concs<-seq(0.01,0.97,0.01)

#create all possible permutations of these numbers with repeats
combos2<-gtools::permutations(length(concs),4,concs,TRUE,TRUE)

#subset the list of possible concentrations so that all that is left are the rows of data
#where all four values (4 columns) in a row (the four material concentrations) sum to 1

# Subset vector to only retain the rows where the sum is equal to 1
subset_vctr <- which(Rfast::rowsums(combos2[, 1:4]) == 1)
combos2<-combos2[subset_vctr, ]

我本质上只是询问哪些行总和等于 1,然后使用该向量对矩阵combos2进行子集化。 Rfast package 包含处理矩阵的快速例程。

这是一个基本的 R 解决方案:

combos2 <- subset(combos2, rowSums(combos2[, 1:4]) == 1)

head(combos2)
     [,1] [,2] [,3] [,4]
[1,] 0.01 0.01 0.01 0.97
[2,] 0.01 0.01 0.02 0.96
[3,] 0.01 0.01 0.03 0.95
[4,] 0.01 0.01 0.04 0.94
[5,] 0.01 0.01 0.05 0.93
[6,] 0.01 0.01 0.06 0.92

这是一种可能更快的方法,避免使用permutations ...

combos2 <- expand.grid(seq(0, .97, 0.01),  #combinations of first three variables
                       seq(0, .97, 0.01),
                       seq(0, .97, 0.01))

combos2$Var4 <- 1 - rowSums(combos2)       #define fourth variable to sum to 1
combos2 <- combos2[combos2$Var4 >= 0, ]    #delete any rows with Var4<0

为了您的信息,Rfast 还包含具有排列的快速函数。

暂无
暂无

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

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