Home > other >  R find index of a variable and subset a lsit
R find index of a variable and subset a lsit

Time:12-01

I have a list that looks like this

#Make dataframes
df1 = data.frame(x = c("a", "b", "c"), y = 1:3, stringsAsFactors = F)
df2 = df1 %>% mutate(y = y*2)
df3 = df1 %>% mutate(y = y*3)

#Make a name for each dataframe
myvar = "fname"

#Combine name and dataframe into a list
mylist = list(myvar, df1)

#Add the other dataframes and name to the list (done in a loop for my bigger dataset
list2 = list(myvar, df2)
mylist = rbind(mylist, list2)

list3  = list(myvar, df3)
mylist = rbind(mylist, list3)

I want to pull a subset of the list with all the data associated with "c"

  x y
3 c 3
  x y
3 c 6
  x y
3 c 9

This is what I tried but it doesn't work

#Find all instances of "c"
picksite = "c"

site_indices = which(mylist[,2] == picksite)
mylist[site_indices,]

Any suggestions on how to do this, or even a link to better understand lists? Thanks so much.

CodePudding user response:

Wrapping the which inside of lapply will solve this problem:

lapply(mylist[,2], FUN = function(i) i[which(i == "c"),])
$mylist
  x y
3 c 3

$list2
  x y
3 c 6

$list3
  x y
3 c 9

CodePudding user response:

Using tidyverse, we can loop over the list with map and use if_any to filter

library(dplyr)
library(purrr)
map(mylist[,2], ~ .x %>%
    filter(if_any(everything(), ~ .x == "c")))

-output

$mylist
  x y
1 c 3

$list2
  x y
1 c 6

$list3
  x y
1 c 9
  • Related