简体   繁体   中英

use dplyr to create dummy variables

I'm trying to do the folowing using dplyr :

Suppose you have the data.frame y and you want to create a new variable based on values of var1

y <- data.frame(var1 = rnorm(100))
y$var2 <- 0
y$var2[y$var1 > 0.5] <- 1

Is it possible to do this using dplyr 's mutate and filter ?

Try mutate :

> y <- data.frame(var1 = (-2):2)
> y %>% mutate(var2 = as.numeric(var1 > 0.5))
  var1 var2
1   -2    0
2   -1    0
3    0    0
4    1    1
5    2    1

Update: dplyr now uses %>% in place of %.%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM