Evaluate an expression to data frame columns

Viewed 60

I want to evaluate multiple expressions for a given data frame and return a data frame with the transformed columns. What I used to do was :

library(dplyr)
df <- data.frame(A = 1:5, B = 6:10)
expr <- c("A+B", "A-B")
names(expr) <- c("V1", "V2")
df %>% transmute_(.dots = lazyeval::all_dots(expr))

This code will return the desired output:

  V1 V2
1  7 -5
2  9 -5
3 11 -5
4 13 -5
5 15 -5

However, both transmute_ and lazyeval are deprecated and was wondering if there's a better way to do that? The real data contain many expressions and columns so was also looking for a more time efficient method.

1 Answers

This way is a bit convoluted, but maybe suitable for your purpose:

library(tidyverse)
expr %>% map(str2expression) %>% map(eval, envir = df) %>% as.data.frame()
#  V1 V2
#1  7 -5
#2  9 -5
#3 11 -5
#4 13 -5
#5 15 -5

#Check
identical(df %>% transmute_(.dots = lazyeval::all_dots(expr)), 
          expr %>% map(str2expression) %>% 
                   map(eval, envir = df) %>% 
                   as.data.frame()
          )

# [1] TRUE
Related