如何将df col名称列表传递给purrr :: map公式?

时间:2017-10-11 21:55:21

标签: r purrr

我想将列名列表传递给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')

我知道有一个全新的“quosure”编程与dplyr 0.7编程,但这似乎是相当常见的事情,并且早于此。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您可以执行上述操作,但如果可以,最好不要在使用purrr时处理非标准评估。这是另一种方法:

list_vars %>% 
  map(~ t.test(cars[[.x]], cars$mpg))

这会利用t.test的默认S3方法,而不是类formula的S3方法。所以,正在发生的事情是,您将向量作为前两个参数,而不是在数据帧中输入并告诉t.test在哪里查看。

答案 1 :(得分:0)

另一种方法:

map(list_vars, ~ t.test(mpg ~ col, data = cars %>% rename_("col" = .x)))
相关问题