Question

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?

Was it helpful?

Solution

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 %.%

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top