您可以使用dplyrcross()来遍历成对的列吗?
我有 18 对变量,我想对它们进行成对数学运算以计算 18 个新变量。将公式应用于一列时,dplyr 中的 cross() 函数非常方便。有没有办法将 cross() 应用于成对的列?
简单划分 2 个变量的小例子(我的实际代码会更复杂,一些 ifelse,...):
library(tidyverse)
library(glue)
# filler data
df <- data.frame("label" = c('a','b','c','d'),
"A" = c(4, 3, 8, 9),
"B" = c(10, 0, 4, 1),
"error_A" = c(0.4, 0.3, 0.2, 0.1),
"error_B" = c(0.3, 0, 0.4, 0.1))
# what I want to have in the end
# instead of just 2 (A, B), I have 18
df1 <- df %>% mutate(
'R_A' = A/error_A,
'R_B' = B/error_B
)
# what I'm thinking about doing to use both variables A and error_A to calculate the new column
df2 <- df %>% mutate(
across(c('A','B'),
~.x/{HOW DO I USE THE COLUMN WHOSE NAME IS glue('error_',.x)}
.names = 'R_{.col}'
)
回答
一种选择是map/reduce。指定感兴趣的列('nm1'),在它们中循环map,select来自数据集的那些列,reduce通过划分,rename列绑定(_dfc)之后的列,并将它们与原始数据集绑定
library(dplyr)
library(purrr)
library(stringr)
nm1 <- c('A', 'B')
map_dfc(nm1, ~ df %>%
select(ends_with(.x)) %>%
reduce(., `/`) ) %>%
rename_all(~ str_c('R_', nm1)) %>%
bind_cols(df, .)
-输出
# label A B error_A error_B R_A R_B
#1 a 4 10 0.4 0.3 10 33.33333
#2 b 3 0 0.3 0.0 10 NaN
#3 c 8 4 0.2 0.4 40 10.00000
#4 d 9 1 0.1 0.1 90 10.00000
或另一种选择 across
df %>%
mutate(across(c(A, B), ~
./get(str_c('error_', cur_column() )), .names = 'R_{.col}' ))
# label A B error_A error_B R_A R_B
#1 a 4 10 0.4 0.3 10 33.33333
#2 b 3 0 0.3 0.0 10 NaN
#3 c 8 4 0.2 0.4 40 10.00000
#4 d 9 1 0.1 0.1 90 10.00000