Home > Mobile >  Filter data frame and append result to existing lists R
Filter data frame and append result to existing lists R

Time:11-17

I want to filter a dataframe column (col_A) and append the output to existing lists. The filters to apply to col_A are included in a vector col_A_filters.

My question is how to create a function for this with R.

Example:

Df <- data.frame(
  col_A = c("abc","def"),
  col_B = c(123,456)
)

# existing lists:
abc <- list()
def <- list()


col_A_filters <- c("abc", "def")

The output should be that to each of the lists abc and def the filtered rows of Df are added.

CodePudding user response:

Here is a way with mget and append.

Df <- data.frame(
  col_A = c("abc","def"),
  col_B = c(123,456)
)

# existing lists:
abc <- list()
def <- list()

col_A_filters <- c("abc", "def")

l <- mget(col_A_filters, envir = .GlobalEnv)
for(i in col_A_filters) {
  new <- Df[Df$col_A == i, ]
  l[[i]] <- append(l[[i]], new)
  l[[i]] <- as.data.frame(l[[i]])
}
list2env(l, envir = .GlobalEnv)
#> <environment: R_GlobalEnv>

abc
#>   col_A col_B
#> 1   abc   123

def
#>   col_A col_B
#> 1   def   456

Created on 2022-11-16 with reprex v2.0.2

CodePudding user response:

Another option using {purrr}:

library(tidyverse)
col_A_filters <- c("abc", "def")
col_A_filters |> 
  as.list()|> 
  map(~Df |> 
        filter(str_detect(col_A, .x))) |> 
  set_names(col_A_filters)

Output:

$abc
  col_A col_B
1   abc   123

$def
  col_A col_B
1   def   456
  •  Tags:  
  • r
  • Related