如何在不使用%>%的情况下以常规格式编写以下代码?

时间:2017-05-16 05:20:25

标签: r ggplot2 charts dplyr

# install package for this customized spider chart
devtools::install_github("ricardo-bion/ggradar", dependencies=TRUE)

library(ggradar)
suppressPackageStartupMessages(library(dplyr))
library(scales)   

mtcars %>%
   add_rownames( var = "group" ) %>%
   mutate_each(funs(rescale), -group) %>%
   tail(4) %>% select(1:10) -> mtcars_radar

这是创建蜘蛛/极地图的代码

 ggradar(mtcars_radar) #gives you the following spider chart

enter image description here

2 个答案:

答案 0 :(得分:4)

这很简单:

mtcars[] <- lapply(mtcars, scales::rescale)
mtcars$group <- rownames(mtcars)
rownames(mtcars) <- NULL    # not necessary, really
mtcars_radar <- tail(mtcars, 4)[, c(length(mtcars), 1:9)]    # move group to first variable

mtcars_radar
#>             group       mpg cyl      disp        hp      drat        wt
#> 29 Ford Pantera L 0.2297872 1.0 0.6981791 0.7491166 0.6728111 0.4236768
#> 30   Ferrari Dino 0.3957447 0.5 0.1843352 0.4346290 0.3963134 0.3214012
#> 31  Maserati Bora 0.1957447 1.0 0.5734597 1.0000000 0.3594470 0.5259524
#> 32     Volvo 142E 0.4680851 0.0 0.1244699 0.2014134 0.6221198 0.3239581
#>          qsec vs am
#> 29 0.00000000  0  1
#> 30 0.11904762  0  1
#> 31 0.01190476  0  1
#> 32 0.48809524  1  1

答案 1 :(得分:1)

%>%只是获取前面的表达式/函数的结果,并将其作为表达式/函数的第一个参数传递给它。所以以下是等同的......

library(ggradar)
library(dplyr)
library(scales)    

mtcars <- add_rownames(mtcars, var = "group")
mtcars <- mutate_each(mtcars, funs(rescale), -group)
mtcars <- tail(mtcars, 4)
mtcars <- select(mtcars, 1:10)
mtcars_radar <- mtcars

ggradar(mtcars_radar)