我有一个叫description
的tibble:
description <- structure(list(col1 = "age", col2 = "> 7 months", col3 = "<= 7 months"), row.names = c(NA,
-1L), class = c("tbl_df", "tbl", "data.frame"))
> description
# A tibble: 1 × 3
col1 col2 col3
<chr> <chr> <chr>
1 age > 7 months <= 7 months
和一个称为my_df
的数据帧:
my_df <- structure(list(ID = c("ID1", "ID2", "ID3", "ID4", "ID5", "ID6"
), age = structure(c(1L, 2L, 1L, 2L, 2L, 2L), .Label = c("<= 7 months",
"> 7 months"), class = "factor")), row.names = c("ID1", "ID2",
"ID3", "ID4", "ID5", "ID6"), class = "data.frame")
> my_df
ID age
ID1 ID1 <= 7 months
ID2 ID2 > 7 months
ID3 ID3 <= 7 months
ID4 ID4 > 7 months
ID5 ID5 > 7 months
ID6 ID6 > 7 months
我目前有以下功能:
updated_df <- purrr::pmap(description, function(col1, col2, col3) {
subset(
my_df,
age == col2
)
})
这将产生:
[[1]]
ID age
ID2 ID2 > 7 months
ID4 ID4 > 7 months
ID5 ID5 > 7 months
ID6 ID6 > 7 months
但是我想使用变量col1
而不是age
.我try 了以下方法,但都不起作用:
updated_df <- purrr::pmap(description, function(col1, col2, col3) {
subset(
my_df,
col1 == col2
)
})
updated_df <- purrr::pmap(description, function(col1, col2, col3) {
subset(
my_df,
!!as.name(col1) == col2
)
})
updated_df <- purrr::pmap(description, function(col1, col2, col3) {
subset(
my_df,
!!col1 == col2
)
})
我哪里做错了/用col1
代替age
的正确方法是什么?