简体   繁体   English

我可以使用 dplyr mutate 根据两列来划分值吗?

[英]Can I use dplyr mutate to divide values based on two columns?

I have the following test data:我有以下测试数据:

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'))

I'd like the to divide the values of year 1 by the values of year 0 based on Trt groups.我想根据 Trt 组将第 1 年的值除以第 0 年的值。 I've been using the group_by and mutate functions but can't quite figure it out.我一直在使用 group_by 和 mutate 函数,但不太明白。

Using group_by + mutate you could do:使用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

or using pivot_wider and pivot_longer you could do:或使用pivot_widerpivot_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.

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