Home > Net >  How to filter data with condition dependent on dataframe names
How to filter data with condition dependent on dataframe names

Time:12-31

I have a list of tables produced by lapply and give them names

FIF.result <- lapply (c("A5", "A6"), FIF.calc)

and give them names

names(FIF.result) <- c("A5", "A6")

I want to apply a filter with a condition dependent on dataframe names.

Pseudocode:

FIF.result <- lapply (FIF.result, function (x) {
  if (names (x) == "A5") {
    x <- x %>% filter (wskaznik > 20)
  } else {
    x <- x %>% filter (wskaznik > 25)
  }
})

CodePudding user response:

You can use Map, i.e. mapply(..., SIMPLIFY = FALSE)), a multivariate version of lapply().

Map(function(df, nms) {
  if (nms == "A5") {
    df %>% filter(wskaznik > 20)
  } else {
    df %>% filter(wskaznik > 25)
  }
}, FIF.result, names(FIF.result))

Its purrr equivalent is imap():

library(purrr)

imap(FIF.result, ~ {
  if (.y == "A5") {
    .x %>% filter(wskaznik > 20)
  } else {
    .x %>% filter(wskaznik > 25)
  }
})

where .x represents each data.frame in the list and .y is the list name.


Example Data
FIF.result <- list(A5 = data.frame(wskaznik = 1:30),
                   A6 = data.frame(wskaznik = 1:30))
Output
$A5
   wskaznik
1        21
2        22
3        23
4        24
5        25
6        26
7        27
8        28
9        29
10       30

$A6
  wskaznik
1       26
2       27
3       28
4       29
5       30
  • Related