我的清单如下:
tryout<- list(c("stomach:biopsy", ",colon:biopsy", ",stomach:biopsy"),
character(0), character(0), "oesophagus:biopsy", character(0),
character(0))
我想"stomach:biopsy"
用数字1代替术语。我想用case_when
fromdplyr
我试过了:
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?
由于空白元素很多,我们可以创建一个索引来检查是否至少有一个元素。根据模式细分list
和replace
i1 <- lengths(tryout) > 0
tryout[i1] <- lapply(tryout[i1], function(x) replace(x, x == 'stomach:biopsy', 1))
如果部分匹配,则grep
在OP的帖子中使用
tryout[i1] <- lapply(tryout[i1], function(x)
replace(x, grep('stomach:biopsy', x), 1))
根据OP的评论,有多种模式需要替换。在这种情况下,最好创建一个键/值数据集或命名的向量,然后执行一个left_join/match
等。在这种情况下,由于它是部分匹配项,因此最好使用regex_left_join
fromfuzzyjoin
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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句