![](/img/trans.png)
[英]dplyr: mutate new column based on multiple columns selected by variable string
[英]Creating new variable with dplyr::mutate based on multiple conditions and corresponding variable names passed by string vector (or tidyselect)
我很確定這是之前討論過的,但我很難用語言表達這個問題:例如,我正在尋找這個數據框......
iris %>%
mutate(has_petal_1.4 = Petal.Length == 1.4 | Petal.Width == 1.4,
width_greater_1 = Sepal.Width > 1 & Petal.Width > 1)
...無需明確命名條件中的變量。 有沒有辦法使用字符串向量傳遞變量名? 不幸的是,這似乎不起作用:
varsel <- c('Petal.Length', 'Petal.Width')
iris %>%
mutate(has_petal_1.4 = 1.4 %in% c(!!! syms(varsel)))
此外,我想知道在 mutate() function 中是否有使用 tidyselect 的解決方案。 到目前為止,我使用了新的方便的 cross() function 來改變多個變量。 是否也可以在條件下使用它? 這是另一個不起作用的示例:
iris %>%
mutate(has_petal_1.4 = across(c(starts_with('Petal')), function(x) {1.4 %in% x}))
非常感謝任何幫助。
有多種方法,一種選擇是c_across
library(dplyr) # >= 1.0.0
iris %>%
rowwise %>%
mutate(has_petal_1.4 = any(c_across(varsel) == 1.4),
width_greater_1 = all(c_across(ends_with('Width')) > 1)) %>%
ungroup
# A tibble: 150 x 7
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species has_petal_1.4 width_greater_1
# <dbl> <dbl> <dbl> <dbl> <fct> <lgl> <lgl>
# 1 5.1 3.5 1.4 0.2 setosa TRUE FALSE
# 2 4.9 3 1.4 0.2 setosa TRUE FALSE
# 3 4.7 3.2 1.3 0.2 setosa FALSE FALSE
# 4 4.6 3.1 1.5 0.2 setosa FALSE FALSE
# 5 5 3.6 1.4 0.2 setosa TRUE FALSE
# 6 5.4 3.9 1.7 0.4 setosa FALSE FALSE
# 7 4.6 3.4 1.4 0.3 setosa TRUE FALSE
# 8 5 3.4 1.5 0.2 setosa FALSE FALSE
# 9 4.4 2.9 1.4 0.2 setosa TRUE FALSE
#10 4.9 3.1 1.5 0.1 setosa FALSE FALSE
# … with 140 more rows
或者使用rowSums
的更快選項
iris %>%
mutate(has_petal_1.4 = rowSums(select(., varsel) == 1.4) > 0,
width_greater_1 = rowSums(select(., ends_with('Width')) > 1) == 2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.