Using mutate_at to create new columns by using other columns in the same data frame

风流意气都作罢 提交于 2019-12-07 20:35:17

问题


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))


来源:https://stackoverflow.com/questions/55157692/using-mutate-at-to-create-new-columns-by-using-other-columns-in-the-same-data-fr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!