如何在R中使用labelled::look_for并结合purrr批量处理变量列表
问题
我希望从数据框df中选取单个变量,得到与look_for(df, 'country')一致的查询结果,但当前自定义函数返回的是df中所有变量的结果。现有变量名存储在列表variabs中,请问能否使用purrr::map或pmap对列表中的每个变量批量获取目标结果?
示例代码
library(tidyverse) library(labelled) df <- tibble(country = c(1,2,1), sex = c(1,1,2)) df$country <- labelled( c(1, 2, 1), c(PT = 1, UK = 2), label = "Country of birth" ) df$sex <- labelled( c(1, 1, 2), c(Male = 1, Female = 2), label = "Assigned sex at birth" ) variabs <- list('country', 'sex') # 期望的结果:仅返回country变量的信息 look_for(df, 'country') #> pos variable label col_type values #> 1 country Country of birth dbl+lbl [1] PT #> [2] UK # 当前自定义函数:返回所有变量的信息,不符合预期 showAt <- function(db, v){ at <- db %>% pull(.data[[v]]) return(look_for(db, at)) } showAt(df, 'country') #> pos variable label col_type values #> 1 country Country of birth dbl+lbl [1] PT #> [2] UK #> 2 sex Assigned sex at birth dbl+lbl [1] Male #> [2] Female showAt(df, variabs[[1]]) #> pos variable label col_type values #> 1 country Country of birth dbl+lbl [1] PT #> [2] UK #> 2 sex Assigned sex at birth dbl+lbl [1] Male #> [2] Female Created on 2022-08-24 by the reprex package (v2.0.1)
解决方案
1. 修正自定义函数
问题出在showAt函数的逻辑:你用pull(.data[[v]])获取了变量的取值,但look_for的第二个参数需要的是变量名/标签的匹配模式,不是变量的取值。直接把变量名v传给look_for即可:
showAt <- function(db, v){ look_for(db, v) }
测试这个修正后的函数,showAt(df, 'country')会返回和look_for(df, 'country')完全一致的结果。
2. 用purrr::map批量处理
直接用map遍历variabs列表中的每个变量名,调用修正后的showAt函数:
# 批量获取每个变量的查询结果 map(variabs, ~showAt(df, .x))
运行后会得到一个列表,每个元素对应一个变量的look_for查询结果:
[[1]] pos variable label col_type values 1 1 country Country of birth dbl+lbl [1] PT [2] UK [[2]] pos variable label col_type values 1 2 sex Assigned sex at birth dbl+lbl [1] Male [2] Female
3. (可选)合并结果为数据框
如果想把所有变量的结果合并成单个数据框,可以用map_dfr:
map_dfr(variabs, ~showAt(df, .x))
输出:
pos variable label col_type values 1 1 country Country of birth dbl+lbl [1] PT 2 2 sex Assigned sex at birth dbl+lbl [1] Male
内容的提问来源于stack exchange,提问作者sbac
相关产品推荐
相关产品推荐

