使用R中的子集来过滤字符串。

huangapple go评论84阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年1月6日 20:41:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定