我想將一列col名稱傳遞給purrr :: map公式。 這裏是我的問題的reprex:如何將一個df col名稱列表傳遞給purrr :: map公式?
library(dplyr)
library(purrr)
#Make a toy df of w vars of 2 levels
cars <- mtcars %>%
select(mpg, cyl, carb) %>%
filter(cyl == 4 | cyl == 6,
carb == 2 | carb == 4)
#normal fn call, works fine
t.test(mpg ~ cyl, data = cars)
t.test(mpg ~ carb, data = cars)
Welch Two Sample t-test
data: mpg by cyl
t = 3.5371, df = 7.0689, p-value = 0.009356
Welch Two Sample t-test
data: mpg by carb
t = 3.5371, df = 7.0689, p-value = 0.009356
#Make list of cols
list_vars <- names(cars[,-1])
list_vars
[1] "cyl" "carb"
#Attempt map with formula fn call
map(list_vars, ~ t.test(mpg ~ .x, data = cars))
#Results in this error
Error in model.frame.default(formula = mpg ~ .x, data = cars) :
variable lengths differ (found for '.x')
我知道有與dplyr 0.7「quosure」編程的整個新的世界,但是這似乎喜歡的事,是相當普遍的早一點。謝謝你的幫助。
可以用'formula'建立經由'paste'下式:'地圖(list_vars,〜t.test(式(糊( 「MPG〜」,.X)) ,data = cars))' – aosmith