Masi Masi - 1 month ago 20
R Question

How to get Ages by IDs in R?

Data

ID,Age,Gender
100,69,male
101,75,female
102,84,female
103,,male
104,66,female


Code

DF <- read.csv("/home/masi/data.csv", header = T)
ids <- c(101,103)
ages <- DF[which(ids), ]$Age


Output

Error in which(ids) : argument to 'which' is not logical
Calls: makeMatrixPlot -> [ -> [.data.frame -> which
Execution halted


You can do
DF[which(gender, ]$ID
but why not for
Age
.

OS: Debian 8.5

R: 3.1.1

Answer

Subsetting with which() like this is not a good idea. Use the subset() function with the %in% operator to test for membership in a vector.

ages <- subset(DF, ID %in% ids)$Age

or use the match function for subsetting

ages <- DF[match(ids, DF$ID),"Age"]