简体   繁体   中英

Remove participants based on a certain criteria

I have an experiment with numerous participants and their choices. For simplicity, let's assume the following:

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

Now, I would like to entirely remove certain participants. For example those who made at least one choice above 10. So in the example above, because participant 2, made one choice above 10, I entirely remove him: The final data should look:

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

How can I do it?

Thanks!

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

with this code you don't even need to install any package.

Using R base, without need of loading packages. The example uses variable names, instead of position, for better overview of the solution.

# 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,]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM