【问题标题】:Looping a dataframe deleting process in R在R中循环数据框删除过程
【发布时间】:2021-12-09 13:04:32
【问题描述】:

我想知道如何在下面循环我的代码以使其对其他数据更具功能性和通用性(当前数据只是一个玩具):

FIRST,我使用sample()data 中选择一个study,然后在filter() 的行中选择outcome == outcome_to_remove。这给出了datat 的输出。

SECOND,我使用sample()datat中选择一个study,然后filter()其中的outcome == outcome_to_remove2的行。这给出了最终输出。

我们可以循环这个过程吗?

编辑: 我想添加到我的代码中的唯一条件是循环前后的length(unique(data$study)) 应该始终保持不变。也就是说,study 不可能在 FIRST 步骤中丢失其 outcome == "A",在 SECOND 步骤中丢失 outcome == "B",因此整个研究将被删除。

(data <- expand_grid(study = 1:5, group = 1:2, outcome = c("A", "B")))

n = 1
#====-------------------- FIRST:  
studies_to_remove = sample(unique(data$study), size = n)
outcome_to_remove = c("A")
             
datat <- data %>%
  filter(
    !(    study %in% studies_to_remove &
        outcome %in% outcome_to_remove
    ))

#====------------------- SECOND:
studies_to_remove2 = sample(unique(datat$study), size = n)
outcome_to_remove2 = c("B")

datat %>%
  filter(
    !(    study %in% studies_to_remove2 &
        outcome %in% outcome_to_remove2
    ))

【问题讨论】:

    标签: r dataframe function loops purrr


    【解决方案1】:

    借助for循环-

    data <- tidyr::expand_grid(study = 1:5, group = 1:2, outcome = c("A", "B"))
    
    n = 1
    set.seed(9873)
    outcome_to_remove <- unique(data$outcome)
    unique_study <- unique(data$study)
    
    for(i in outcome_to_remove) {
      studies_to_remove = sample(unique_study, size = n)
      outcome_to_remove = i
      unique_study <- setdiff(unique_study, studies_to_remove)
      cat('\nDropping study ', studies_to_remove, 'and outcome ', outcome_to_remove)
      data <- data %>%
        filter(
          !( study %in% studies_to_remove &
             outcome %in% outcome_to_remove
          ))
    }
    
    #Dropping study  3 and outcome  A
    #Dropping study  1 and outcome  B
    
    data
    #   study group outcome
    #   <int> <int> <chr>  
    # 1     1     1 A      
    # 2     1     2 A      
    # 3     2     1 A      
    # 4     2     1 B      
    # 5     2     2 A      
    # 6     2     2 B      
    # 7     3     1 B      
    # 8     3     2 B      
    # 9     4     1 A      
    #10     4     1 B      
    #11     4     2 A      
    #12     4     2 B      
    #13     5     1 A      
    #14     5     1 B      
    #15     5     2 A      
    #16     5     2 B      
    

    【讨论】:

    • 1.我的代码完全符合您在问题中显示的内容,但带有一个循环。唯一的区别是您使用了新变量 (datat),但我使用了相同的变量 (data)。 2.您的代码没有完全删除研究。如果您删除了某项研究的outcome = 'A',但outcome = 'B' 仍然存在于datat 中的同一研究中。我的代码以同样的方式工作。
    • @rnorouzian 然后你需要相应地改变你的问题。你的问题并没有反映你真正想要做什么。使用您问题中的相同代码,也有可能从输出中删除整个研究。
    猜你喜欢
    • 2020-03-13
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    相关资源
    最近更新 更多