【问题标题】:Combining sample() and group_by() from tidyvese结合来自 tidyvese 的 sample() 和 group_by()
【发布时间】:2021-12-10 15:14:29
【问题描述】:

下面,我试图在我的data 中的每个study 中随机选择group 值的行,如何?

好吧,我们首先group_by(study),然后根据以下条件决定在每个study 中选择group 的行之一:

group_row <- sapply(1:length(unique(data$study)), 
                     function(i)sample(0:2, 1, replace = TRUE))

对于group_by(study) 中的每个study:

如果group_row 是1,请选择group == 1 行中的study。

如果group_row 是2,则选择group == 2 行中的study。

如果group_row 是0,则选择该study 的所有行。

我尝试了以下方法但没有成功?

library(tidyverse)

(data <- expand_grid(study=1:3,group=1:2,outcome=c("A","B"), time=0:1) %>%
    as.data.frame())


lapply(1:2, function(i){
data %>% dplyr::group_by(group) %>% 
    filter(group == if(group_row[i] ==0) unique(data$group) else group_row[i]) %>% 
  dplyr::ungroup() %>% arrange(study,group,outcome,time)
})

【问题讨论】:

    标签: r dataframe dplyr tidyverse sample


    【解决方案1】:

    您可以编写一个函数来为每个study 选择一行并按组应用该函数。

    library(dplyr)
    
    return_rows <- function(x) {
      n <- sample(0:2, 1)
      #If n = 0 select all rows else 
      #select row for corresponding group
      if(n == 0) TRUE else x == n
    }
    
    
    data %>%
      group_by(study) %>%
      filter(return_rows(group)) %>%
      ungroup()
    

    【讨论】:

    • 您的快捷方式问题似乎是 RStudio 中的一个错误 (community.rstudio.com/t/…) - 我猜开发人员正在处理它,但也值得在该页面上发布您的信息
    • 当您仅对 1 个数字进行抽样时,则不会。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2022-11-23
    • 2018-02-05
    相关资源
    最近更新 更多