簡體   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