First code:
sample data:
vector1 <- data.frame("name"="a","age"=10,"gender"="m")
vector2 <- data.frame("name"="b","age"=33,"gender"="m")
vector3 <- data.frame("name"="b","age"=58,"gender"="f")
list <- list(vector1,vector2,vector3)
sql <- list()
for(i in 1:length(list)){
print(list[[1]]) # access dataframe
sql[[i]]<-
sqldf(paste0("select name,gender,count(name) from ",list[[i]]," group by gender "))
}
How to loop the data frame correctly using sqldf function? I have tried list[[1]] or list[1] in the sqldf function to do the test but it will return no such table or syntax error. In the loop function, I can access the data frame. Is it possible to use this format?
print(str(list))
List of 3
$ :'data.frame': 1 obs. of 3 variables:
..$ name : Factor w/ 1 level "a": 1
..$ age : num 10
..$ gender: Factor w/ 1 level "m": 1
$ :'data.frame': 1 obs. of 3 variables:
..$ name : Factor w/ 1 level "b": 1
..$ age : num 33
..$ gender: Factor w/ 1 level "m": 1
$ :'data.frame': 1 obs. of 3 variables:
..$ name : Factor w/ 1 level "b": 1
..$ age : num 58
..$ gender: Factor w/ 1 level "f": 1
NULL
Second:
This code is my expectation.
f<- lapply(list, function(dataframe) {
sql <-
sqldf("select name,gender,count(name) from dataframe group by gender ")
})
print(f)
This is the output.
> print(f)
[[1]]
name gender count(name)
1 a m 1
[[2]]
name gender count(name)
1 b m 1
[[3]]
name gender count(name)
1 b f 1
Is it possible to use the first code to access the list? How to fix it when I want to use paste function to access each data frame in a list.