我对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]发布于 2019-11-20 04:31:53
像这样创建一个子集向量怎么样:
#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包包含处理矩阵的快速例程。
发布于 2019-11-20 04:35:09
这是一个基本的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发布于 2019-11-20 05:45:39
这里有一个可能更快的方法,避免使用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<0https://stackoverflow.com/questions/58941852
复制相似问题