【问题标题】:Remove participants based on a certain criteria根据特定条件移除参与者
【发布时间】:2019-01-02 11:20:56
【问题描述】:

我对众多参与者及其选择进行了一项实验。 为简单起见,我们假设以下内容:

part<-c(1,1,1,2,2,2,3,3,3)
choice<-c(6,2,9,2,3,18,3,6,8)
study<-cbind(part,choice)

       part choice
 [1,]    1      6
 [2,]    1      2
 [3,]    1      9
 [4,]    2      2
 [5,]    2      3
 [6,]    2     18
 [7,]    3      3
 [8,]    3      6
 [9,]    3      8

现在,我想完全删除某些参与者。比如在10以上做出了至少一个选择的人。所以在上面的例子中,因为参与者2,在10以上做出了一个选择,我完全删除了他:最终的数据应该是:

      part choice
[1,]    1      6
[2,]    1      2
[3,]    1      9
[4,]    3      3
[5,]    3      6
[6,]    3      8

我该怎么做?

谢谢!

【问题讨论】:

  • 使用dplyr,您可以使用study %&gt;% group_by(part) %&gt;% filter(all(choice &lt; 10))

标签: r filtering subset data-manipulation


【解决方案1】:
library(dplyr)
 study %>% 
   group_by(part) %>% 
   filter(max(choice)<10)
# A tibble: 6 x 2
# Groups:   part [2]
   part choice
  <dbl>  <dbl>
1     1      6
2     1      2
3     1      9
4     3      3
5     3      6
6     3      8

【讨论】:

    【解决方案2】:
    removed = which(study[ , 2]>10);
    study = study[!(study[ , 1] %in% study[removed, 1]), ];
    
    study
         part choice
    [1,]    1      6
    [2,]    1      2
    [3,]    1      9
    [4,]    3      3
    [5,]    3      6
    [6,]    3      8
    

    使用此代码,您甚至不需要安装任何软件包。

    【讨论】:

      【解决方案3】:

      使用 R 基础,无需加载包。该示例使用变量名称而不是位置,以便更好地了解解决方案。

      # Create object to be used in dataframe.
      part   <- c(1,1,1,2,2,2,3,3,3)
      choice <- c(6,2,9,2,3,18,3,6,8)
      # Create dataframe.
      study  <- data.frame(part, choice)
      
      # Find rows in column [study$choice]
      find_rows <- which(study$choice > 10)
      # Find participant that matches [find_rows]
      participant_to_be_deleted <- study[find_rows,1]
      
      # Remove all rows that has found participant in [study$part].
      result <- study[study$part!=participant_to_be_deleted,]
      

      【讨论】:

        猜你喜欢
        • 2014-03-14
        • 1970-01-01
        • 2020-03-27
        • 2020-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多