Maxence
Maxence

Reputation: 23

Using lapply with parse() function

I want to parse() through a list of conditions using lapply, to then be able to use them as a filter for a data set. Consider this for instance :

library(ggplot2)
argList <- list(c("mpg"), "manufacturer == \"audi\" ", "year > 2002")
argList <- lapply(argList, FUN = parse, text = argList)
data <- do.call(filter, argList)

The parse() function takes a text = " " argument for input, representing the string of character to be parsed. I can't get lapply() to use each element of the list instead of the whole list. Indeed, lapply(argList, FUN = parse, text = argList) returns

[[1]]
expression(mpg, manufacturer == "audi", year > 2002)

[[2]]
expression(mpg, manufacturer == "audi", year > 2002)

[[3]]
expression(mpg, manufacturer == "audi", year > 2002)

instead of

[[1]]
mpg

[[2]]
manufacturer == "audi"

[[3]]
year > 2002

Upvotes: 2

Views: 311

Answers (2)

akrun
akrun

Reputation: 887088

We could also use parse_expr from rlang

library(tidyverse)
library(rlang)
do.call(filter, map(argList, parse_expr))
# A tibble: 9 x 11
#  manufacturer model      displ  year   cyl trans drv     cty   hwy fl    class
#  <chr>        <chr>      <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
#1 audi         a4           2    2008     4 manu… f        20    31 p     comp…
#2 audi         a4           2    2008     4 auto… f        21    30 p     comp…
#3 audi         a4           3.1  2008     6 auto… f        18    27 p     comp…
#4 audi         a4 quattro   2    2008     4 manu… 4        20    28 p     comp…
#5 audi         a4 quattro   2    2008     4 auto… 4        19    27 p     comp…
#6 audi         a4 quattro   3.1  2008     6 auto… 4        17    25 p     comp…
#7 audi         a4 quattro   3.1  2008     6 manu… 4        15    25 p     comp…
#8 audi         a6 quattro   3.1  2008     6 auto… 4        17    25 p     mids…
#9 audi         a6 quattro   4.2  2008     8 auto… 4        16    23 p     mids…

data

argList <- list(c("mpg"), "manufacturer == \"audi\" ", "year > 2002")

Upvotes: 1

MrFlick
MrFlick

Reputation: 206197

That's because you are passing the entire argList to parse() and not using the value thats passed via the lapply. Also you'll need to unbox the expression to get the call. Try

argList <- lapply(argList, FUN = function(x) parse(text=x)[[1]])
argList
# [[1]]
# mpg
# 
# [[2]]
# manufacturer == "audi"
# 
# [[3]]
# year > 2002

Upvotes: 3

Related Questions