在`dplyr/across`中,如何排除给定的列

问题描述 投票:0回答:1

dplyr/across
中,我想 *-1 到数字列排除
a1
或 excelue
a1
a2

library(tidyverse)    
raw_data <- data.frame(
  type=c('A','B','C'),
  cat=c("cat1","cat2","cat3"),
  a3=1:3,
  b2=1:3,
  c2=1:3,
  c1=1:3,
  a2=1:3,
  b1=1:3,
  a1=1:3)

#  * -1 to numeric columns exclude a1  
raw_data %>% mutate(across(where(is.numeric)&!='a1',~. *-1))

#  * -1 to numeric columns exclude a1 a2
raw_data %>% mutate(across(where(is.numeric)&!(. %in% c('a1','a2')),~. *-1))
r dplyr across
1个回答
1
投票

across
中的第一个参数是
.cols
,因此只需提供您想要包含或排除的列的向量
c()

library(dplyr)

raw_data |> 
  mutate(across(c(where(is.numeric), -a1, -a2),~ . * -1))

  type  cat a3 b2 c2 c1 a2 b1 a1
1    A cat1 -1 -1 -1 -1  1 -1  1
2    B cat2 -2 -2 -2 -2  2 -2  2
3    C cat3 -3 -3 -3 -3  3 -3  3
© www.soinside.com 2019 - 2024. All rights reserved.