我有一个叫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的正确方法是什么?

推荐答案

如果希望保持在subset以内,则需要捕获并计算完整表达式.例如.

purrr::pmap(description, function(col1, col2, col3) {
  subset(
    my_df,
    eval(rlang::expr(!!rlang::ensym(col1) == col2))
  )
})

如果您愿意使用dplyr::filter而不是subset,您可以执行以下操作:

purrr::pmap(description, function(col1, col2, col3) {
  dplyr::filter(
                my_df,
                !!rlang::ensym(col1) == col2
                )
})

R相关问答推荐

如何删除字符串中重复的字符序列?

从API中抓取R数据SON

管道末端运行功能

ggplot2中的X轴显示数值,单位为百,而不是十

自动变更列表

如何自定义3D散点图的图例顺序?

IMF IFS数据以R表示

多个过滤器内的一个盒子在仪表板Quarto

如何提取所有完美匹配的10个核苷酸在一个成对的匹配与生物字符串在R?>

根据现有列的名称和字符串的存在进行变异以创建多个新列

仅 Select 超过9行的CSV文件

如何将SAS数据集的列名和列标签同时包含在r中GT表的表首?

调换行/列并将第一行(原始数据帧的第一列)提升为标题的Tidyr类似功能?

如何将一个方阵分解成没有循环的立方体

如何在R中使用混合GAM模型只对固定的影响因素进行适当的预测?

如何筛选截止年份之前最后一个测量年度的所有观测值以及截止年份之后所有年份的所有观测值

有没有办法将不等长的列表转换为R中的数据帧

如何构建一个for循环来循环处理动物ID?

我需要使用ggplot2制作堆叠条形图

生存时间序列的逻辑检验