Saturday, 15 March 2014

r - Add sublist element values if sublist doesn't already exist and else overwrite it -



r - Add sublist element values if sublist doesn't already exist and else overwrite it -

if have nested list

m=list(list(a=1,b=2,c=3),list(a=1,b=2,c=3))

and have values element d in vector, how can add together these values nested list m if sublist d doesn't exist, , else overwrite values of sublist d?

lapply(1:length(m),function(i) c(m[[i]],d=d[[i]]))

adds values of vector d=c(1,3), problem if twice, maintain on adding sublists d, don't want - rather them overwritten. (i add/replace 1st vector element 1st sublist, 2nd 2nd sublist etc)

how do in r?

the modifylist function might useful in case. run

lapply(m, modifylist, list(d=1:3))

and replace values of sublists in m values in list specify.

if had vector of d values , wanted add together 1 each list, then

map(modifylist, m, lapply(c(1,3), function(x) list(d=x)))

may improve option.

r list nested-lists sublist

No comments:

Post a Comment