我有一份清单,如下:
tryout<- list(c("stomach:biopsy", ",colon:biopsy", ",stomach:biopsy"),
character(0), character(0), "oesophagus:biopsy", character(0),
character(0))我想用数字1替换术语"stomach:biopsy"。我想用来自dplyr的case_when来实现
我试过了:
lapply(tryout, function(x)
x %>%
mutate(group = case_when(
grepl("stomach:biopsy",x ) ~ 1
)))但是我得到了一个错误:
Error in UseMethod("mutate_") :
no applicable method for 'mutate_' applied to an object of class "character"那么,如何为嵌套列表运行case_when呢?
发布于 2019-01-11 21:07:19
由于有许多空白元素,我们可以创建一个索引来检查是否至少有一个元素。基于模式的list和replace子集
i1 <- lengths(tryout) > 0
tryout[i1] <- lapply(tryout[i1], function(x) replace(x, x == 'stomach:biopsy', 1))如果是部分匹配,则使用grep,就像在OP的post中一样
tryout[i1] <- lapply(tryout[i1], function(x)
replace(x, grep('stomach:biopsy', x), 1))更新
根据OP的评论,有多个模式需要替换。在这种情况下,最好创建一个键/val数据集或命名向量,然后执行left_join/match等操作。在这种情况下,由于是部分匹配,因此最好使用fuzzyjoin中的regex_left_join
library(fuzzyjoin)
library(tidyverse)
# create a key/val tibble
d1 <- tibble(key = c("stomach:biopsy", "colon:biopsy",
"oesophagus:biopsy"), val = 1:3)
# loop through the list elements having at least one element
# left join with the key/val dataset
# pull the column of 'val'
# update the list elements
tryout[i1] <- map(tryout[i1], ~
tibble(key = .x) %>%
regex_left_join(d1) %>%
pull(val))发布于 2019-01-11 21:11:16
检查此解决方案:
library(tidyverse)
tryout <-
tibble(
var = list(
c("stomach:biopsy", ",colon:biopsy", ",stomach:biopsy"),
character(0),
character(0),
"oesophagus:biopsy",
character(0),
character(0))
)
tryout %>%
mutate(var = map(var, ~case_when(
.x == 'stomach:biopsy' ~ '1',
TRUE ~ .x
))) %>%
pull(var)https://stackoverflow.com/questions/54147090
复制相似问题