Combine/merge lists by elements names (list in list)

前端 未结 5 938
渐次进展
渐次进展 2021-01-11 20:42

I have two lists, whose elements have partially overlapping names, which I need to merge/combine together into a single list, element by element:

My question is rela

5条回答
  •  爱一瞬间的悲伤
    2021-01-11 21:21

    This is a kind of a nested merge function which seems to produce the output you desire. I feel like there should be a more simple way but I can't think of one. It will prefer values from the first parameter, but will merge with values from the second parameter if there is a matching name or index.

    nestedMerge<-function(a,b) {
        if(is.list(a) & is.list(b)) {
            out<-list()
            if(!is.null(names(a))) {
                for(n in names(a)) {
                    if(n %in% names(b) && !is.null(b[[n]])) {
                        out<-append(out, list(Recall(a[[n]], b[[n]])))
                    } else {
                        out<-append(out, list(a[[n]]))
                    }
                    names(out)[length(out)]<-n
                }
            } else {
                for(i in seq_along(a))
                    if(i <=length(b) && !is.null(b[[i]])) {
                        out<-append(out, Recall(a[[i]], b[[i]]))
                    } else {
                        out<-append(out, list(a[[i]]))
                    }
            }
            return(out)
        } else {
            return(list(c(a,b)))
        }
    }
    
    #and now, use the function
    nestedMerge(l.1,l.2)
    

提交回复
热议问题