ckluss - 1 year ago 182

R Question

to change data types I can use something like

`l1 <- c("fac1","fac2","fac3")`

l2 <- c("dbl1","dbl2","dbl3")

dat[,l1] <- lapply(dat[,l1], factor)

dat[,l2] <- lapply(dat[,l2], as.numeric)

with

`dplyr`

`dat <- dat %>% mutate(`

fac1 = factor(fac1), fac2 = factor(fac2), fac3 = factor(fac3),

dbl1 = as.numeric(dbl1), dbl2 = as.numeric(dbl2), dbl3 = as.numeric(dbl3)

)

is there a more elegant (shorter) way in dplyr?

thx

Christof

Answer Source

You can use the standard evaluation version of `mutate_each`

(which is `mutate_each_`

) to change the column classes:

```
dat %>% mutate_each_(funs(factor), l1) %>% mutate_each_(funs(as.numeric), l2)
```