r - 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.
解决方案
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')
推荐阅读
- apache-kafka - Kafka - 阅读一包消息
- java - 从 BaseAdapter 的 getView 中获取方法中的值
- react-native - React Native Linking 'openUrl':如何选择默认浏览器?
- ubuntu - 导入的虚拟机生成 IP 失败
- android - 如何在 DialogFragment 被关闭时不保存它的滚动位置?
- c# - 实体类 DataAnnotations 核心 2.0 中的自引用
- android - 在 Android NDK 中使用 google 测试
- string - 将 BigInterger 转换为十六进制字符串表示
- android - Android Studio 将设备显示为 someAlphanumeric[null]
- php - 您的 SQL 语法有错误;检查与您的 MariaDB 对应的手册