英文:
To filter string using subset in R
问题
我有这些数据。
结构(list(val =“108_front_outside,lake,106_front_later”),
row.names = c(NA,
-1L),class = c(“tbl_df”,“tbl”,“data.frame”))
我想使用“val”的子集来过滤某些内容。
“val”的子集就像“108_front_outside”,“lake”,“106_front_later”,“108_front_out, lake”这样(总共8个组件)。
如果它运行良好,A =“106_front_later, lake”将被过滤,
但B =“lake, others”将不会被过滤,因为它包含其他组件(“others”)。
我应该如何解决这个问题?
英文:
I have this data.
structure(list(val = "108_front_outside, lake, 106_front_later"),
row.names = c(NA,
-1L), class = c("tbl_df", "tbl", "data.frame"))
I would like to filter something using subset of val
.
The subset of val
is like "108_front_outside"
, "lake"
, "106_front_later"
, "108_front_out, lake"
... (totaling 8 components)
If it works well, A = "106_front_later, lake" would be filtered,
but B = "lake, others" would be not filtered because it contains the other component ("others").
How should I approach this issue?
答案1
得分: 1
val = "108_front_outside, lake, 106_front_later"
allwords = unlist(strsplit(val, ","))
test = c("108_front_outside", "lake", "106_front_later", "108_front_out, lake", "lake, others")
sapply(test, function(i) all(sapply(strsplit(i, ",")[[1]], function(j) any(grepl(j, allwords)))))
108_front_outside lake 106_front_later
TRUE TRUE TRUE
108_front_out, lake lake, others
TRUE FALSE
英文:
Hopefully I get you correct, you can try the following with a combination of grepl and strsplit on ",". If there's more to you, you should explain the logic of your filtering:
val = "108_front_outside, lake, 106_front_later"
allwords = unlist(strsplit(val,","))
test = c("108_front_outside", "lake", "106_front_later",
"108_front_out, lake", "lake, others")
sapply(test,function(i)all(sapply(strsplit(i,",")[[1]],function(j)any(grepl(j,allwords)))))
108_front_outside lake 106_front_later
TRUE TRUE TRUE
108_front_out, lake lake, others
TRUE FALSE
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论