[英]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.