Reputation: 137
I have a problem with a loop over different data.frames to select certain rows. Here is a simple example.
I have here three data.frames:
Died.At <- c(22,40,72,41)
Writer.At <- c(16, 18, 36, 36)
Sex <- c("MALE", "MALE", "MALE", "FEMALE")
europe<-data.frame(Died.At, Writer.At, First.Name, Second.Name, Sex)
Died.At <- c(22,40,72,41)
Writer.At <- c(50, 28, 46, 16)
Sex <- c("MALE", "MALE", "MALE", "FEMALE")
africa<-data.frame(Died.At, Writer.At, First.Name, Second.Name, Sex)
Died.At <- c(22,40,72,41)
Writer.At <- c(30, 18, 96, 66)
Sex <- c("MALE", "MALE", "MALE", "FEMALE")
asia<-data.frame(Died.At, Writer.At, First.Name, Second.Name, Sex)
I want to select the individuals with [Writer.At<=20] And I want to rewrite every database with just these individuals. So I tried this:
for (i in c(europe,africa,asia)){
A.i<-i[i$Writer.At>=20]
}
What I get is this warning: Error in i$Writer.At: $ operator is invalid for atomic vectors
I don't understand why. Could you help me to solve this problem?
Upvotes: 0
Views: 38
Reputation: 1576
Your solution doesn't work because "i" refers to values in each data frame, not the name of the data frame. One solution is like this:
for (i in c("europe","africa","asia")){
df<-get(i)
df<-df[df$Writer.At>=20,]
assign(paste0("A",i), df)
}
Alternatively, you could combine the dataframes in a list and do the following:
writers <- list(europe=europe, africa=africa,asia=asia)
writersafter20 <- lapply(writers, subset, Writer.At>=20)
Upvotes: 1