R function to combine lists but prioritize the values in one of them -
i'm trying make function combine multiple lists, between 2 , 4, weed out duplicates , (if possible) prioritize values of 1 of lists. possible? it's better explained code:
passopts <- function(in1 = list(), in2 = list(), in3 = list(), in4 = list(){ c(in1, in2, in3, in4) } opts1 <- list(a = 1, b = 2, c = 4) opts2 <- list(a = 1, b = 2, c = 4) opts3 <- list(a = 5, b = 10) combinedopts <- passopts(opts1, opts2, opts3)
ideally want possible 'prioritize' list different rest, in case want combinedopts
list of a = 5, b = 10, c = 4
. i'm using way set , combine default , user input options. thanks
**solved, ended doing realized latest input (i.e. 3 inputs in3) 1 want use default, did follows
passopts <- function(in1 = list(), in2 = list(), in3 = list(), in4 = list()){ if(length(in4) != 0){ in4names <- names(in4) rlist <- in4 temp <- c(in1,in2,in3) tempnames <- names(temp) for(i in 1:length(tempnames)){ nam <- tempnames[i] if(!(nam %in% in4names)){ in4names <- c(in4names,nam) rlist[nam] <- temp[nam] } } }else if(length(in3) != 0){ in3names <- names(in3) rlist <- in3 temp <- c(in1,in2) tempnames <- names(temp) for(i in 1:length(tempnames)){ nam <- tempnames[i] if(!(nam %in% in3names)){ in3names <- c(in3names, nam) rlist[nam] <- temp[nam] } } }else if(length(in2) != 0){ in2names <- names(in2) rlist <- in2 temp <- in1 tempnames <- names(temp) for(i in 1:length(tempnames)){ nam <- tempnames[i] if(!(nam %in% in2names)){ in2names <- c(in2names, nam) rlist[nam] <- temp[nam] } } }else{ return(in1) } return(rlist) }
looks likes looking of unique number.
here how do: 1. aggregate input lists 2. find out unique 1 each key
passopts <- function(listoflist){ reslist = list() # reduce lists key (l in listoflist){ (i in 1:length(l)){ key = names(l[i]) value = l[[i]] reslist[[key]] = c(reslist[[key]], value) } } # found diffent 1 each key finddiff <- function(elements){ counttable = table(elements) mincount = min(counttable) return(names(counttable)[counttable == mincount]) } return(lapply(reslist, fun=finddiff)) } opts1 <- list(a = 1, b = 2, c = 4) opts2 <- list(a = 1, b = 2, c = 4) opts3 <- list(a = 5, b = 10) combinedopts <- passopts(list(opts1, opts2, opts3))
Comments
Post a Comment