Dplyr: get error when use mutate with a standarized dataframe

Created on 2 Mar 2015  路  2Comments  路  Source: tidyverse/dplyr

I got an error message when doing mutate in a standarized dataframe:

 > mtcars=mtcars %>% colwise(scale)() %>% mutate(x1=mpg/60)
 Error: data_frames can only contain 1d atomic vectors and lists

> mtcars=mtcars %>% colwise(scale)() %>% mutate(x1=mpg+cyl)
Error: data_frames can only contain 1d atomic vectors and lists

I don't know why dplyr 0.4.1 is not supported with a standarized data,it is not convenient.

Most helpful comment

scale is returning a matrix, not a numeric:

R> mtcars_scale <- mtcars %>% colwise(scale)()
R> lapply(mtcars_scale, class)
$mpg
[1] "matrix"

$cyl
[1] "matrix"

$disp
[1] "matrix"

$hp
[1] "matrix"

$drat
[1] "matrix"

$wt
[1] "matrix"

$qsec
[1] "matrix"

$vs
[1] "matrix"

$am
[1] "matrix"

$gear
[1] "matrix"

$carb
[1] "matrix"

The fix using mutate_each and funs is easy:

R> mtcars_scale <- mtcars %>% mutate_each(funs( as.numeric(scale(.) )))
R> lapply(mtcars_scale, class)
$mpg
[1] "numeric"

$cyl
[1] "numeric"

$disp
[1] "numeric"

$hp
[1] "numeric"

$drat
[1] "numeric"

$wt
[1] "numeric"

$qsec
[1] "numeric"

$vs
[1] "numeric"

$am
[1] "numeric"

$gear
[1] "numeric"

$carb
[1] "numeric"

All 2 comments

scale is returning a matrix, not a numeric:

R> mtcars_scale <- mtcars %>% colwise(scale)()
R> lapply(mtcars_scale, class)
$mpg
[1] "matrix"

$cyl
[1] "matrix"

$disp
[1] "matrix"

$hp
[1] "matrix"

$drat
[1] "matrix"

$wt
[1] "matrix"

$qsec
[1] "matrix"

$vs
[1] "matrix"

$am
[1] "matrix"

$gear
[1] "matrix"

$carb
[1] "matrix"

The fix using mutate_each and funs is easy:

R> mtcars_scale <- mtcars %>% mutate_each(funs( as.numeric(scale(.) )))
R> lapply(mtcars_scale, class)
$mpg
[1] "numeric"

$cyl
[1] "numeric"

$disp
[1] "numeric"

$hp
[1] "numeric"

$drat
[1] "numeric"

$wt
[1] "numeric"

$qsec
[1] "numeric"

$vs
[1] "numeric"

$am
[1] "numeric"

$gear
[1] "numeric"

$carb
[1] "numeric"

Thank you so much,pimentel!

Was this page helpful?
0 / 5 - 0 ratings