user1491868 - 1 year ago 87
R Question

# R Subset Nested List

Using R base, I would like to subset a nested list where the subset condition changes for each list element. Below is an example. Thank you.

``````#CREATE EXAMPLE NESTED LIST
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"), YEAR = c(2014:2016), NUM = c(1:3))
DF <- lapply(1:3, function(i) DF[[i]] <- lapply(2014:2016,
function(t) DF[with(DF, YEAR == t), ]))

#I WOULD LIKE TO SIMPLIFY THIS PART AS MUCH AS POSSIBLE
DF[[1]][[1]] <- DF[[1]][[1]][with(DF[[1]][[1]], NUM == 1), ]
DF[[1]][[2]] <- DF[[1]][[2]][with(DF[[1]][[2]], NUM == 1), ]
DF[[1]][[3]] <- DF[[1]][[3]][with(DF[[1]][[3]], NUM == 1), ]

DF[[2]][[1]] <- DF[[2]][[1]][with(DF[[2]][[1]], NUM == 2), ]
DF[[2]][[2]] <- DF[[2]][[2]][with(DF[[2]][[2]], NUM == 2), ]
DF[[2]][[3]] <- DF[[2]][[3]][with(DF[[2]][[3]], NUM == 2), ]

DF[[3]][[1]] <- DF[[3]][[1]][with(DF[[3]][[1]], NUM == 3), ]
DF[[3]][[2]] <- DF[[3]][[2]][with(DF[[3]][[2]], NUM == 3), ]
DF[[3]][[3]] <- DF[[3]][[3]][with(DF[[3]][[3]], NUM == 3), ]
``````

You can use `Map` to bind the predicate values to each list of data frames, then loop through the inner list and do the subset:

``````values = c(1,2,3)

Map(function(dfs, val) lapply(dfs, function(df) subset(df, NUM == val)), DF, values)

#[[1]]
#[[1]][[1]]
#   NAME YEAR NUM
#1 FRANK 2014   1
#2  TONY 2014   1
#3    ED 2014   1

#[[1]][[2]]
#   NAME YEAR NUM
#4 FRANK 2015   1
#5  TONY 2015   1
#6    ED 2015   1

#[[1]][[3]]
#   NAME YEAR NUM
#7 FRANK 2016   1
#8  TONY 2016   1
#9    ED 2016   1

#[[2]]
#[[2]][[1]]
#    NAME YEAR NUM
#10 FRANK 2014   2
#11  TONY 2014   2
#12    ED 2014   2

# ...
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download