How to convert string to coefficient and set contrasts using dplyr / magrittr pipelines

I have a rather specific question: how can I make a string into a factor and set its contrasts inside the pipe?

Say I have matched below

tib <- data_frame (a = rep(c("a","b","c"),3, each = T), val = rnorm(9))

Now I could use two separate lines

tib$a <- factor(tib$a)
contrasts(tib$a) <- contr.sum(3)

But what if I wanted to perform the same actions on a channel from dplyr?

+4
source share
2 answers

Well, that was a fun puzzle, since I hadn't used do () before, but this works for me:

tib <- data.frame (a = rep(c("a","b","c"),3, each = T), val = rnorm(9)) 

tib = tib %>% mutate(a = factor(a)) %>% do({function(X) {contrasts(X$a) <- contr.sum(3); return(X)}}(.))

contrasts(tib$a)

result:

  [,1] [,2]
a    1    0
b    0    1
c   -1   -1

Hope this helps!

EDIT: comment for explanation, see below:

This was also new to me. As I understand it, in the do () call it says

{func}(.)

, ., do. func,

function(X) {operation to perform on X}

:

{function(X) {operation to perform on X}}(.)

. X, " ".

+2

R . , . contrasts<- .

mutate(tib, a=`contrasts<-`(factor(a), , contr.sum(3)))
+3

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


All Articles