[英]How can I Loop through a dataframe with Dplyr and use mutate to change values of some cells based on a condition?
[英]Can I use dplyr mutate to divide values based on two columns?
我有以下測試數據:
df <- data.frame(Year = c('1' , '1' , '1' , '0' , '0' , '0') ,
Trt = c('A' , 'B' , 'C' , 'A' , 'B' , 'C') ,
value = c('2' , '5' , '3' , '6' , '3' , '4'))
我想根據 Trt 組將第 1 年的值除以第 0 年的值。 我一直在使用 group_by 和 mutate 函數,但不太明白。
使用group_by
+ mutate
你可以這樣做:
df <- data.frame(Year = c('1' , '1' , '1' , '0' , '0' , '0') ,
Trt = c('A' , 'B' , 'C' , 'A' , 'B' , 'C') ,
value = c('2' , '5' , '3' , '6' , '3' , '4'))
library(dplyr, warn = FALSE)
df %>%
mutate(value = as.numeric(value)) %>%
group_by(Trt) |>
mutate(value = ifelse(Year == 1, value / value[Year == 0], value)) |>
ungroup()
#> # A tibble: 6 × 3
#> Year Trt value
#> <chr> <chr> <dbl>
#> 1 1 A 0.333
#> 2 1 B 1.67
#> 3 1 C 0.75
#> 4 0 A 6
#> 5 0 B 3
#> 6 0 C 4
或使用pivot_wider
和pivot_longer
你可以這樣做:
df %>%
mutate(value = as.numeric(value)) %>%
tidyr::pivot_wider(names_from = Year, values_from = value) %>%
mutate(`1` = `1` / `0`) |>
tidyr::pivot_longer(-Trt, names_to = "Year") |>
arrange(desc(Year))
#> # A tibble: 6 × 3
#> Trt Year value
#> <chr> <chr> <dbl>
#> 1 A 1 0.333
#> 2 B 1 1.67
#> 3 C 1 0.75
#> 4 A 0 6
#> 5 B 0 3
#> 6 C 0 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.