簡體   English   中英

dplyr如何執行按行條件的mutate操作

[英]dplyr how to do the rowwise conditional mutate operation

我想在虹膜表中增加一列,以便在相同的Species中,第一行是NA,如果Petal.Width與最后一行(在右上方)相同,則其余行是1,否則,則是0 Petal.Width與最后一行不同。

如何使用dplyr實現這一目標? 需要下面的“更改”列。

   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

dplyr具有lag()函數:

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM