首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用rowsum或rowSums设置子集

使用rowsum或rowSums设置子集
EN

Stack Overflow用户
提问于 2019-11-20 03:51:13
回答 4查看 283关注 0票数 0

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

代码语言:javascript
复制
#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]
EN

回答 4

Stack Overflow用户

发布于 2019-11-20 04:31:53

像这样创建一个子集向量怎么样:

代码语言:javascript
复制
#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包包含处理矩阵的快速例程。

票数 1
EN

Stack Overflow用户

发布于 2019-11-20 04:35:09

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

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2019-11-20 05:45:39

这里有一个可能更快的方法,避免使用permutations...

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58941852

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档