Standard dplyr mutate_each_ rating

I puzzle over the implementation of SE mutate_each_ in dplyr. What I want to do is subtract the value in one column in DF from each column in DF.

Here is a minimal working example of what I want to accomplish using an aperture dataset (I delete the Views column so that it is all numeric). I subtract the Petal.Width column from each column. But I need the column name to be a variable, like "My.Petal.Width"

# Remove Species column, so that we have only numeric data
iris_numeric <- iris %>% select(-Species)

# This is the desired result, using NSE
result_NSE <- iris_numeric %>% mutate_each(funs(. - `Petal.Width`))

# This is my attempt at using SE 
SubtractCol <- "Petal.Width"
result_SE <- iris_numeric %>% mutate_each_(funs(. - as.name(SubtractCol)))

# Second attempt
SubtractCol <- "Petal.Width"
Columns <- colnames(iris_numeric)
mutate_call = lazyeval::interp(~.-a, a = as.name(SubtractCol))
result_SE <- iris_numeric %>% mutate_each_(.dots = setNames(list(mutate_call), Columns))

I get various errors:

Error in colwise_(tbl, funs_(funs), vars) : 
  argument "vars" is missing, with no default

Error in mutate_each_(., .dots = setNames(list(mutate_call), Columns)) : 
  unused argument (.dots = setNames(list(mutate_call), Columns))

Please help and many thanks in advance.

+4
source share
2 answers

What you are looking for is the SE version funs, i.e. funs_:

library(lazyeval); library(dplyr)
SubtractCol <- "Petal.Width"
iris %>% mutate_each(funs_(interp(~.-x, x = as.name(SubtractCol))), -Species) %>% head
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1          4.9         3.3          1.2           0  setosa
#2          4.7         2.8          1.2           0  setosa
#3          4.5         3.0          1.1           0  setosa
#4          4.4         2.9          1.3           0  setosa
#5          4.8         3.4          1.2           0  setosa
#6          5.0         3.5          1.3           0  setosa

mutate_each_, , "-Species", /.

, mutate_each_ summarise_each_ .dots.

+8

result_SE <- iris_numeric %>% 
mutate_each_(funs(paste0('. - ',as.name(SubtractCol)))

character,

+1

Source: https://habr.com/ru/post/1624302/


All Articles