问题
I'm still very new to R and haven't found any answer so far. Sorry to finally ask.
Edition with a quick example: I want to compute a multidimensional development index based on South Africa Data. My list is composed of individual information for each year, so basically df1 is about year 1 and df2 about year2.
df1<-data.frame(var1=c(1, 1,1), var2=c(0,0,1), var3=c(1,1,0))
df2<-data.frame(var1=c(1, 0,1), var2=c(1,0,1), var3=c(0,1,0))
mylist <-list (df1,df2)
You can find here a very simplified working index function:
myindex <- function(x, dimX, dimY){
econ_i<- ( x[dimX]+ x[dimY] )
return ( (1/length(econ_i))*sum(econ_i) )
}
myindex(df1, "var2", "var3")
Then I have my dataframe of variables I want to use for my index
mydf <- data.frame(set1=c("var1", "var2"), set2=c("var2", "var3"))
I'm using a function to get arguments from database such as:
pick_values <-function(x){
vect <-c()
for(i in x){
vect <- c(vect, i)
}
return(vect)
}
I'd like to set up a lapply loop such that I apply my function for my list, for all sets of arguments in my dataframe. In other words, I'd like to compute my index for both years, with all sets of variables I can use. //end Edit
I've tried many unsuccessful things so far. For instance:
lapply(mylist, myindex, lapply(mydf,pick_values))
Thanks a lot for your help!
回答1:
Okay, I don't like your mydf
name nor that it has factors, so I rename it args
because it has function arguments and I set stringsAsFactors = F
:
args <- data.frame(set1=c("var1", "var2"), set2=c("var2", "var3"), stringsAsFactors = F)
We'll also write a wrapper for myindex
that accepts a vector of arguments instead of dimX
and dimY
:
myindex2 = function(x, d) {
myindex(x, d[1], d[2])
}
Then we can nest lapply
like this:
lapply(mylist, function(m) lapply(args, myindex2, x = m))
# $df1
# $df1$set1
# [1] 4
#
# $df1$set2
# [1] 3
#
#
# $df2
# $df2$set1
# [1] 4
#
# $df2$set2
# [1] 3
来源:https://stackoverflow.com/questions/47837411/lapply-function-with-arguments-i-want-to-pick-from-a-dataframe-with-a-loop