簡體   English   中英

雙循環得到 R 中的 dataframe (tidyverse)

[英]Double looping to get a dataframe in R (tidyverse)

我想在 5 個不同的回合中重復sample(1:11, 1) 6 次。 在最后的 output 中,我想要一個data.frame ,其中每一輪都是一行(見下文)。

這在tidyverse (例如purrr::map_df )或 BASE R 中可以實現嗎?

round1 4 5 6 7 8 9
round2 3 2 1 4 4 1
round3 5 4 2 2 1 1
round4 7 7 7 7 7 1
round5 1 8 8 8 8 1

我們可以使用replicate

t(replicate(5, sample(1:11, 6, replace = TRUE)))

正如@thelatemail 提到的,我們只能sample一次並將數據放入矩陣中。

nr <- 5
nc <- 6
matrix(sample(1:11, nr * nc, replace = TRUE), nr, nc)

為什么不使用lapply對 6 個元素進行 5 次采樣。 示例中的替換標志提供了多次拉動相同數字的機會。

 data.frame(do.call(rbind, lapply(1:5,function(x) sample(1:11, 6, replace=T)))

正如 OP 詢問的purrr ,這是一個 tidyverse 解決方案,它獲取預期的 output 中指定的行名稱:

library(tidyverse)

rounds <- paste0("round", 1:5) 

rounds %>% 
  setNames(rounds) %>% 
  map_dfc(~sample(1:11, 6, replace = TRUE)) %>% 
  t()

       [,1] [,2] [,3] [,4] [,5] [,6]
round1    1   11   10    6    5   10
round2    9    2    3    3    2   10
round3    8    8    2   11    6    7
round4    1    7    8    6   11   10
round5    1    7    7    3    1    8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM