簡體   English   中英

R - dplyr - mutate_if 多個條件

[英]R - dplyr - mutate_if multiple conditions

我想根據多個條件改變一列。 例如,對於最大值為 5 且列名包含“xy”的每一列,應用一個函數。

df <- data.frame(
  xx1 = c(0, 1, 2),
  xy1 = c(0, 5, 10),
  xx2 = c(0, 1, 2),
  xy2 = c(0, 5, 10)
)
> df

xx1 xy1 xx2 xy2
1   0   0   0   0
2   1   5   1   5
3   2  10   2  10

df2 <- df %>% mutate_if(~max(.)==10, as.character)
> str(df2)
'data.frame':   3 obs. of  4 variables:
 $ xx1: num  0 1 2
 $ xy1: chr  "0" "5" "10"
 $ xx2: num  0 1 2
 $ xy2: chr  "0" "5" "10"
#function worked
df3 <- df %>% mutate_if(str_detect(colnames(.), "xy"), as.character)
> str(df3)
'data.frame':   3 obs. of  4 variables:
 $ xx1: num  0 1 2
 $ xy1: chr  "0" "5" "10"
 $ xx2: num  0 1 2
 $ xy2: chr  "0" "5" "10"
#Worked again

現在當我嘗試將它們結合起來時

df4 <- df %>% mutate_if((~max(.)==10) & (str_detect(colnames(.), "xy")), as.character)

(~max(.) == 10) & (str_detect(colnames(.), "xy")) 中的錯誤:操作僅適用於數字、邏輯或復雜類型

我錯過了什么?

必須使用names而不是列colnames

df4 <- df %>% mutate_if((max(.)==10 & str_detect(names(.), "xy")), as.character)

更簡潔的方法是使用跨越從dplyr

df4 <- df %>% mutate(across(c(where(function(x)max(x)==10),contains('xy')),as.character))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM