如何仅对特定行使用 mutate() +across()

How to use mutate() +across() only for specific rows

数据:

df <- tribble(
  ~name, ~val.I, ~val.V, ~`val.%`,
  "Peter", 123, 12.4, 14,
  "Peter in %", 111, 532, 57,
  "Harald", 2222, 3333, 444,
  "Harald in %", 22, 15, 203,
)

我想对包含 .I.V 的行进行变异(函数:将值除以 100),但仅适用于列 in % 中包含字符串 in % 的行=19=]姓名。我知道一个简单的 for 循环解决方案,但无法用 dplyr 解决。非常感谢任何提示! :)

base R中的可能解决方案:

library(tibble)

df <- tribble(
  ~name, ~val.I, ~val.V, ~`val.%`,
  "Peter", 123, 12.4, 14,
  "Peter in %", 111, 532, 57,
  "Harald", 2222, 3333, 444,
  "Harald in %", 22, 15, 203,
)

df[grepl("in \%",df$name), grep(".V|.I", names(df))] <- 
       df[grepl("in \%",df$name), grep(".V|.I", names(df))] /100

#> # A tibble: 4 × 4
#>   name          val.I   val.V `val.%`
#>   <chr>         <dbl>   <dbl>   <dbl>
#> 1 Peter        123      12.4       14
#> 2 Peter in %     1.11    5.32      57
#> 3 Harald      2222    3333        444
#> 4 Harald in %    0.22    0.15     203

dplyr:

library(dplyr)

df %>% 
 mutate(across(contains(c(".V",".I")), ~ if_else(grepl("in \%",name), .x/100, .x)))

#> # A tibble: 4 × 4
#>   name          val.I   val.V `val.%`
#>   <chr>         <dbl>   <dbl>   <dbl>
#> 1 Peter        123      12.4       14
#> 2 Peter in %     1.11    5.32      57
#> 3 Harald      2222    3333        444
#> 4 Harald in %    0.22    0.15     203

带有 mutateacrossdplyr 选项,对特定列使用 matches。您可以使用以下代码:

library(dplyr)

df %>% 
  mutate(across(matches(".I|.V"), ~ if_else(row_number() %in% grep("in %", name), ./100, .)))

输出:

# A tibble: 4 × 4
  name          val.I   val.V `val.%`
  <chr>         <dbl>   <dbl>   <dbl>
1 Peter        123      12.4       14
2 Peter in %     1.11    5.32      57
3 Harald      2222    3333        444
4 Harald in %    0.22    0.15     203