如何使用case_when从列表中删除元素

时间:2019-01-25 13:06:28

标签: r

我有一个嵌套的字符串列表,我想在满足grepl条件时在新列中输入一个值,我也想从嵌套列表中删除该元素

我的列表如下(嵌套在数据框中)

#define PP_CONCAT1(x,y) x ## y
#define PP_CONCAT(x,y) PP_CONCAT1(x,y)
#define PP_IS_INT_int 1
#define PP_IS_INT_signed 1 /* "signed" alone is the same type as "int" */
#if PP_CONCAT(PP_IS_INT_, WORD) && defined(__builtin_clrsb)

所需结果:

list( "Normal Mucosa Throughout", "Mitotic Lesion- See Text Above", 
    "Normal", 
    c("Mitotic", "Hiatus Hernia"), "Normal Mucosa Throughout", 
    "HALO RFA to Barrett's oesophagus", "Barretts oesophagus", 
    c("Barrett's oesophagus ", "EMR"))

我的FindingsAfterProcessing DiagnosisCode Normal Mucosa Throughout other C159 Normal other Hiatus Hernia C159 Normal Mucosa Throughout other HALO RFA to Barrett's oesophagus other Barretts oesophagus other Barrett's oesophagus other EMR

case_when

如何将其应用于嵌套列表,并在找到元素后也将其删除?

1 个答案:

答案 0 :(得分:0)

map中尝试purrr(您也可以只加载tidyverse):

library(tidyverse)

df %>%
  mutate(
    DiagnosisCode = map(
      FindingsAfterProcessing, ~ case_when(
        any(grepl("mitotic", tolower(.x))) ~ "C159",
        any(grepl("emr", tolower(.x))) ~ "EMR",
        TRUE ~ "other")
      ),
    FindingsAfterProcessing = map(
      FindingsAfterProcessing, ~ .x[!grepl("mitotic|emr", tolower(.x))]
      )
  )

此处的输出为:

           FindingsAfterProcessing DiagnosisCode
1         Normal Mucosa Throughout         other
2                                           C159
3                           Normal         other
4                    Hiatus Hernia          C159
5         Normal Mucosa Throughout         other
6 HALO RFA to Barrett's oesophagus         other
7              Barretts oesophagus         other
8            Barrett's oesophagus            EMR

这不是100%对应于您想要的输出,但是我想您的输出中有错字?

之所以这样说,是因为我的输出是基于您提供的列表的;我把它变成了数据框列:

df <- data.frame(FindingsAfterProcessing = I(list( "Normal Mucosa Throughout", "Mitotic Lesion- See Text Above", 
                                  "Normal", 
                                  c("Mitotic", "Hiatus Hernia"), "Normal Mucosa Throughout", 
                                  "HALO RFA to Barrett's oesophagus", "Barretts oesophagus", 
                                  c("Barrett's oesophagus ", "EMR"))))