Generate a function based upon name data in a csv file opened in R -
i have dataframe of variable names , weightings.
example:
names <- c("a","b","c") weightings <- c(1,2,3) df <- cbind(names,weightings)
i need generate function data such.
myfun <- function(x,data){ data[x,"a"]*1+data[x,"b"]*2+data[x,"c"]*3}
i have dataframe named data column names match a, b, , c , apply myfun data on rows.
the issue have size of names , weightings vector can vary. working 5 names , weightings want generate new function "myfun" such.
newnames <- c("a","b","c","d","e") newweightings <- c(1,2,3,4,5) myfun <- function(data){ data[x,"a"]*1+data[x,"b"]*2+data[x,"c"]*3+data[x,"d"]*4+data[x,"e"]*5}
is there easy way automate creation of function give code, , .csv file of column names , weightings , generate new function.
what strategy this. use function make function
getmyfunction <- function(columns, weights) { stopifnot(length(columns)==length(weights)) function(x, data) { rowsums(data[x, columns] * weights) } }
basically rowsums takes care of addition, specify vector of columns @ once, , default *
element-wise takes care of weights.
then build function like
names <- c("a","b","c") weightings <- c(1,2,3) myfun <- getmyfunction(names, weightings)
and can use with
dd<-data.frame(a=c(1,1), b=c(1,2), c=c(1,3)) myfun(1,dd) # [1] 6 myfun(2,dd) # [1] 13 myfun(1:2,dd) # [1] 6 13
Comments
Post a Comment