简体   繁体   中英

Mutate_each and relative positions of variables

I'm trying to create a new set of variables (using Dplyr's mutate_each) which express each column as a percentage of the column to the left of it.

iris <- mutate_each(iris, funs( testvar = . / ?iris[,.-1]?)  , 2:4)

Should be equivalent to:

iris <- mutate(iris, Sepal.Width_testvar = Sepal.Width / Sepal.Length )
iris <- mutate(iris, Petal.Length_testvar = Petal.Length / Sepal.Width )
iris <- mutate(iris, Petal.Width_testvar = Petal.Width / Petal.Length )

I tried to refer to the variable to the left by trying to get the column number of each . using expressions like iris[, which(names(iris)== .)-1] . None of them were successful as they all returned the following error: Error in mutate_impl(.data, dots) : wrong result size (0), expected 150 or 1 .

We can do this easily in base R by dividing two equally sized datasets where the numerator dataset with columns 2 to 4, and denominator with dataset columns 1 to 3 and assign it to new columns

iris[paste0(names(iris)[2:4], "_testvar")] <- iris[2:4]/iris[1:3]
head(iris)
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species Sepal.Width_testvar Petal.Length_testvar Petal.Width_testvar
#1          5.1         3.5          1.4         0.2  setosa           0.6862745            0.4000000           0.1428571
#2          4.9         3.0          1.4         0.2  setosa           0.6122449            0.4666667           0.1428571
#3          4.7         3.2          1.3         0.2  setosa           0.6808511            0.4062500           0.1538462
#4          4.6         3.1          1.5         0.2  setosa           0.6739130            0.4838710           0.1333333
#5          5.0         3.6          1.4         0.2  setosa           0.7200000            0.3888889           0.1428571
#6          5.4         3.9          1.7         0.4  setosa           0.7222222            0.4358974           0.2352941

Or we can use tidyverse

library(tidyverse)
map2_df(iris[2:4], iris[1:3], `/`) %>%
         setNames(., paste0(names(.), "_testvar")) %>%
         bind_cols(iris, .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM