Using mutate_at to create new columns by using oth

2019-05-27 00:39发布

问题:

Okey, I'm having trouble with something that should be simple. If I have a dataframe like this:

x <- data.frame(a = seq(1,3), b = seq(2,4), c = seq(3,5), d = seq(4,6), b2 = seq(5,7), c2 = seq(6,8), d2 = seq(7,9))

# a b c d b2 c2 d2
# 1 2 3 4 5  6  7
# 2 3 4 5 6  7  8
# 3 4 5 6 7  8  9 

I want to use mutate_at to create new columns based on the result from b/b2, c/c2 etc. When I try:

myvars <- c(2:4)
dvars <- c(5:7)
x <- x %>%
mutate_at(vars(myvars), funs('_new' = vars(myvars) / vars(dvars)))

I get an error "Evaluation error: non-numeric argument to binary operator."

I've also tried using mapply but haven't been able to make it work. The reason I want to use mutate_at is that I want to make changes to the original columns based on the result from this division in the next step.

回答1:

You could directly do

x[myvars]/x[dvars]

#          b         c         d
#1 0.4000000 0.5000000 0.5714286
#2 0.5000000 0.5714286 0.6250000
#3 0.5714286 0.6250000 0.6666667

I am not sure if you could do this with mutate_at however, you can use map2_df from purrr

purrr::map2_df(x[myvars], x[dvars], ~ .x/.y)

OR with mapply

mapply("/", x[myvars], x[dvars])


回答2:

We can make it in a expression and then evaluate with parse_exprs from rlang

library(dplyr)
expr1 <- paste0(names(x)[myvars], "/", names(x)[dvars])
x %>% 
     mutate(!!! rlang::parse_exprs(expr1))


标签: r mutate