繁体   English   中英

将for循环的输出保存在R中

[英]Save the output of a for loop in R

假设我有一个二项式分布,其中n = 12,p = 0.2。 我将此样本分成4个块(组),每个块的组大小为3。然后删除总和等于0的输出。对于其余的输出,我想做的就是将所有剩余的输出合并为一个新的向量。 这是我的代码

set.seed(123)
sample1=rbinom(12,1,0.2)
chuck2=function(x,n)split(x,cut(seq_along(x),n,labels=FALSE))
chunk=chuck2(sample1,4)
for (i in 1:4){
  aa=chunk[[i]]
  if (sum(aa)!=0){
    a.no0=aa
    print(a.no0)
  }
}

这是输出:

[1] 1 1 0
[1] 0 1 0
[1] 0 1 0

我想将这三个输出合并成一个新的向量,例如:

[1] 1 1 0 0 1 0 0 1 0

但我不知道它是如何工作的,请问有什么提示吗?

set.seed(123)
sample1=rbinom(12,1,0.2)
chuck2=function(x,n)split(x,cut(seq_along(x),n,labels=FALSE))
chunk=chuck2(sample1,4)  

int_vector <- c()

for (i in 1:4){
    aa=chunk[[i]]
    if (sum(aa)!=0){
        a.no0=aa
        int_vector <- c(int_vector, a.no0)
    }
}

int_vector
# [1] 1 1 0 0 1 0 0 1 0

创建一个list()并为其分配一个变量名。 接下来,将变量添加到循环中,然后append循环值append到列表中。

new_vector <- list()

for (i in 1:4){
  aa=chunk[[i]]
  if (sum(aa)!=0){
    a.no0=aa
    new_vector <- append(new_vector, a.no0)
  }
}
new_vector

这将返回:

[[1]]
[1] 1

[[2]]
[1] 1

[[3]]
[1] 0

[[4]]
[1] 0

[[5]]
[1] 1

[[6]]
[1] 0

[[7]]
[1] 0

[[8]]
[1] 1

[[9]]
[1] 0

但我认为您想要一个扁平化的向量:

as.vector(unlist(new_vector))

[1] 1 1 0 0 1 0 0 1 0

不能直接解决您的问题,但是可以在没有for循环的情况下完成:

library(dplyr)
set.seed(123)
sample1 <- rbinom(12, 1, 0.2)

as.data.frame(matrix(sample1, ncol = 3, byrow = TRUE)) %>% 
  mutate(test = rowSums(.), id = 1:n()) %>% 
  filter(test > 0) %>% 
  dplyr::select(-test) %>% 
  gather(key, value, -id) %>% 
  arrange(id, key) %>% 
  .$value

没有for循环的两个版本。

数据:

set.seed(123)
sample1 <- rbinom(12, 1, 0.2)

base-R功能版本:

split.sample1 <- split(sample1,cut(seq_along(sample1),4,labels=FALSE))
sumf <- function(x) if(sum(x) == 0) NULL else x
result <- unlist(lapply(split.sample1,sumf),use.names=F)

> result
[1] 1 1 0 0 1 0 0 1 0

管道%>%运算符版本的现代用法:

library(magrittr) # for %>% operator
grp.indx <- cut(seq_along(sample1),4,labels=FALSE)
split.sample1 <- sample1 %>% split(grp.indx)
result <- split.sample1 %>% lapply(sumf) %>% unlist(use.names=F)

> result
[1] 1 1 0 0 1 0 0 1 0

似乎您的函数将伪矩阵作为列表。 而是直接从sample1制作矩阵,然后输出rowSums大于0的向量。

set.seed(123)
sample1 = rbinom(12, 1, 0.2)

chunk_mat = matrix(sample1, ncol = 3, byrow = T)

as.vector(t(chunk_mat[which(rowSums(chunk_mat) != 0), ]))

这里是基准测试-我在全局环境中拥有chuck2 ,但是每个函数仍然必须生成chunk数据帧/矩阵/列表,以便它们像苹果一样。

Unit: microseconds
            expr      min        lq       mean    median        uq       max neval
     cole_matrix   19.902   26.2515   38.60094   43.3505   47.4505    56.801   100
 heds_int_vector 4965.201 5101.9010 5616.53893 5251.8510 5490.9010 23417.401   100
 bwilliams_dplyr 5278.602 5506.4010 5847.55298 5665.7010 5821.5515  9413.801   100
      Simon_base  128.501  138.0010  196.46697  185.6005  203.1515  2481.101   100
  Simon_magrittr  366.601  392.5005  453.74806  455.1510  492.0010   739.501   100

暂无
暂无

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

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