首页 > 解决方案 > R function works but not when I try to map a vector to it

问题描述

I have a data set with columns titled 'a', 'a_yrs', 'b', 'b_yrs', etc. This function works with my data when done manually:

myFunction = function(column){ data%>% count(get(!!column),get(paste0(!!column,'_yrs')))}

so that when I call 'function('a'), it returns a table that counts each unique combination of 'a' and 'a_yrs' (this is the output I want).

I have a list of the columns as "a", "b", etc. However, when I try this, it does not work:

columns = c("a", "b", ... ) columns%>% map(myFunction)

And produces this error:

 `Error in get(paste0("a", "_yrs")) :  object 'a_yrs' not found `

My question is, why would the function work properly in one instance but not when using the map function?

If it matters, the function runs with the map function when I leave out the 'get(paste0(!!column,'_yrs'))' part.

标签: rdictionaryget

解决方案


get寻找环境,容易出现一些问题。相反,我们可以利用 tidyverse 函数将其更改为符号和评估

library(purrr)
library(dplyr)
library(stringr)
myFunction <- function(data, column){
          columnyrs <- str_c(column, "_yrs")
          data %>% 
               count(!! rlang::sym(column), !! rlang::sym(columnyrs))
  }


map(columns, myFunction, data = df1)
#[[1]]
# A tibble: 8 x 3
#  a     a_yrs     n
#  <chr> <int> <int>
#1 a      1980     2
#2 a      1982     2
#3 a      1983     2
#4 b      1979     1
#5 b      1981     1
#6 b      1982     2
#7 c      1979     2
#8 c      1983     3

#[[2]]
# A tibble: 9 x 3
#  b     b_yrs     n
#  <chr> <int> <int>
#1 a      1981     1
#2 a      1982     1
#3 a      1983     1
#4 b      1981     1
#5 b      1982     3
#6 b      1983     3
#7 c      1981     1
#8 c      1982     3
#9 d      1981     1

数据

set.seed(24)
df1 <- data.frame(a = sample(letters[1:3], 15, replace = TRUE), 
a_yrs = sample(1979:1983, 15, replace = TRUE), 
b =sample(letters[1:4], 15, replace = TRUE),
b_yrs = sample(1981:1983, 15, replace = TRUE), stringsAsFactors = FALSE )

columns <- c('a', 'b')

推荐阅读