我正在使用函式和 dplyr。代碼基于這篇文章。我想將一些變數傳遞給 of 的select引數,dplyr然后進行一些分析。當我使用, (coma) 分隔要選擇的變數串列時,R 無法列印結果
library(tidyverse)
df = data.frame(x1 = rnorm(100),
x2 = rnorm(100),
x3 = rnorm(100),
x4 = rnorm(100),
x5 = rnorm(100))
table <- function(items) {
items <- enquo(items)
pretty <- df %>%
select(!!items) %>%
summarise_all(mean)
return(pretty)
}
#x1 only!
table(items = x1)
#> x1
#> 1 0.08593813
#From x1 until X3
table(items = x1:x3)
#> x1 x2 x3
#> 1 0.08593813 -0.1965462 0.02651688
#From x1 until X2 AND from X4 untill X5 (the real df is different.)
table(items = x1:x2, x4:x5)
#> Error in table(items = x1:x2, x4:x5): unused argument (x4:x5)
Created on 2022-01-13 by the reprex package (v2.0.1)
uj5u.com熱心網友回復:
enquos與一起使用可能會更好!!!。對于最后一種情況,連接 ( c)
table <- function(items) {
items <- enquos(items)
pretty <- df %>%
select(!!!items) %>%
summarise_all(mean)
return(pretty)
}
-測驗
> table(items = x1)
x1
1 -0.2262251
> table(items = x1:x3)
x1 x2 x3
1 -0.2262251 0.07106254 0.07618617
> table(items = c(x1:x2, x4:x5))
x1 x2 x4 x5
1 -0.2262251 0.07106254 0.1151052 -0.06535946
注意:table是一個base R函式。因此,最好重命名自定義函式。此外,后綴_all, _at,_each都被棄用,取而代之的是acrossiesummarise(across(everything(), mean))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/412395.html
標籤:
