Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

r - How to filter a table's row based on an external vector?

(1) I have a large table read in R with more than a 10000 of rows and 10 columns.

(2) The 3rd column of the table contain the name of the hospitals. Some of them are duplicated or even more.

(3) I have a vector of hospitals' name, e.g. 10 of them are needed to be study further.

(4) Could you mind to teach me how to extract all the rows in step1 with the names listed in step 3?

Here is a shorter example of my input file;

Patients Treatment Hospital Response 
1        A         YYY      Good 
2        B         YYY      Dead 
3        A         ZZZ      Good 
4        A         WWW      Good 
5        C         UUU      Dead

I have a vector of hospital that I am interested to study further, i.e YYY and UUU. How to generate a output table as follows with R?

Patients Treatment Hospital Response 
1        A         YYY      Good 
2        B         YYY      Dead 
5        C         UUU      Dead
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the %in% operator.

#Sample data
dat <- data.frame(patients = 1:5, treatment = letters[1:5],
  hospital = c("yyy", "yyy", "zzz", "www", "uuu"), response = rnorm(5))

#List of hospitals we want to do further analysis on
goodHosp <- c("yyy", "uuu")

You can either index directly into your data.frame object:

dat[dat$hospital %in% goodHosp ,]

or use the subset command:

subset(dat, hospital %in% goodHosp)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...