Z.Lu
Z.Lu

Reputation: 67

dplyr how to do the rowwise conditional mutate operation

I want to have additional column to the iris table, so that within the same Species, first row is NA, and the rest rows are 1 if Petal.Width is the same as the last row (the row right above), or 0 if Petal.Width is different from last row.

How do I achieve this with dplyr? Change column below is desired.

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species Change
1          5.1         3.5          1.4         0.2  setosa   NA
2          4.9         3.0          1.4         0.2  setosa   0
3          4.7         3.2          1.3         0.2  setosa   0
4          4.6         3.1          1.5         0.2  setosa   0
5          5.0         3.6          1.4         0.2  setosa   0
6          5.4         3.9          1.7         0.4  setosa   1

Upvotes: 0

Views: 1511

Answers (1)

Mako212
Mako212

Reputation: 7292

dplyr has a lag() function:

 iris %>% group_by(Species) %>% 
   mutate(Change = ifelse(lag(Petal.Width)==Petal.Width,0,1))

# A tibble: 150 x 6
# Groups:   Species [3]
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species Change
          <dbl>       <dbl>        <dbl>       <dbl>  <fctr>  <dbl>
 1          5.1         3.5          1.4         0.2  setosa     NA
 2          4.9         3.0          1.4         0.2  setosa      0
 3          4.7         3.2          1.3         0.2  setosa      0
 4          4.6         3.1          1.5         0.2  setosa      0
 5          5.0         3.6          1.4         0.2  setosa      0
 6          5.4         3.9          1.7         0.4  setosa      1
 7          4.6         3.4          1.4         0.3  setosa      1
 8          5.0         3.4          1.5         0.2  setosa      1
 9          4.4         2.9          1.4         0.2  setosa      0
10          4.9         3.1          1.5         0.1  setosa      1

Upvotes: 4

Related Questions