更新时间:2022-12-12 08:30:41
代替解析,一个更简单的选择是使用 map2
遍历列表
与 map
之后。使用 map2
,我们传递感兴趣的列和基于命名的 list
'faclist'
Instead of the parsing, an easier option is to use map2
after looping over the list
with map
. With map2
, we pass the columns of interest and the labels to be changed based on the named list
'faclist'
library(dplyr)
library(purrr)
ldat1 <- map(ldat, ~ {
.x[names(faclist)] <- map2(.x %>%
dplyr::select(names(faclist)),
faclist, ~ factor(.x, labels= .y))
.x} )
-输出
str(ldat1[[1]])
#'data.frame': 39 obs. of 7 variables:
# $ col1: Factor w/ 1 level "Sales": 1 1 NA NA NA NA NA NA 1 NA ...
# $ col2: Factor w/ 1 level "OPS": 1 1 1 1 1 NA NA NA NA 1 ...
# $ col3: Factor w/ 1 level "Management": 1 1 NA NA NA NA NA 1 NA NA ...
# $ col4: Factor w/ 1 level "HR": 1 NA NA NA NA NA NA NA NA NA ...
# $ col5: Factor w/ 2 levels "Local","Overseas": 1 2 1 1 1 2 1 2 2 1 ...
# $ cc1 : num 1 1 1 1 1 1 1 1 1 1 ...
# $ cc2 : num 1 NA 1 1 1 NA 1 NA NA 1 ...
str(ldat1[[2]])
#'data.frame': 18 obs. of 6 variables:
# $ col1: Factor w/ 1 level "Sales": 1 NA NA NA NA NA NA NA 1 NA ...
#$ col2: Factor w/ 1 level "OPS": 1 1 1 1 NA 1 1 1 1 1 ...
# $ col3: Factor w/ 1 level "Management": 1 NA NA NA NA NA NA NA NA NA ...
# $ col4: Factor w/ 1 level "HR": 1 NA NA NA NA NA NA NA NA 1 ...
# $ col5: Factor w/ 2 levels "Local","Overseas": 1 1 1 1 1 1 1 1 1 1 ...
# $ cc1 : num 1 1 1 1 1 1 1 1 1 1 ...
如果它不是列表
,而是两个向量,则只需更改 names(faclist)和带有 labels $的
向量 list
'faclist'
If it is not a list
, but two vectors, then just change the names(faclist)
with the 'col_names' vector and the list
'faclist' with labels
vector
ldat1 <- map(ldat, ~ {
.x[col_names] <- map2(.x %>%
dplyr::select(col_names),
labels, ~ factor(.x, labels= .y))
.x} )