r - Rewrite code using %>% operator -


i tried rewrite code (to learn approach), using %>% operator:

library(arules)  data(adultuci) #https://archive.ics.uci.edu/ml/datasets/census+income  adultuci[["capital-gain"]] <- ordered(cut(adultuci[["capital-gain"]], + c(-inf, 0, median(adultuci[["capital-gain"]][adultuci + [["capital-gain"]] > 0]), inf)), + labels = c("none", "low", "high")) 

is possible do? here attempt:

adultuci[["capital-gain"]] <- ordered %>% cut %>% adultuci[["capital-gain"]],                              + c(-inf, 0, median(adultuci[["capital-gain"]][adultuci[["capital-gain"]] > 0]),                              + inf),labels = c("none", "low", "high") 

this should work:

library(dplyr)  #reproducible data adultuci <- read.csv("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data",header=false)   colnames(adultuci)[13] <- "capital-gain"  #original code originalordered <-    ordered(cut(adultuci[["capital-gain"]],               c(-inf, 0,                  median(adultuci[["capital-gain"]][adultuci[["capital-gain"]] > 0]), inf),               labels = c("none", "low", "high")),           levels = c("none", "low", "high"))  #using dplyr newordered <-    adultuci %>%    select(x=`capital-gain`) %>%    mutate(capitalgainordered=            ordered(              cut(x,c(-inf, 0, median(x[x > 0]), inf),                  labels = c("none", "low", "high")),              levels = c("none", "low", "high"))) %>%    .$capitalgainordered   #test if same identical(originalordered,newordered) #[1] true  str(newordered) #ord.factor w/ 3 levels "none"<"low"<"high": 2 2 2 2 2 2 2 3 3 2 ... 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -