Fastest way to check if values in list are in dataframe using R

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

Fastest way to check if values in list are in dataframe using R

问题

以下是您要翻译的代码部分:

  1. #list
  2. list_vals <- list("a", "b", "c", "d")
  3. #dataframe
  4. df <- data.frame(col1 <- c("1", "a", "c"),
  5. col2 <- c("24a", "d", "b"))
  6. #function to check presence
  7. pmt_present <- function(x) {
  8. present <- any(df==x)
  9. return(present)
  10. }
  11. #run check for vals in df
  12. present_list <- lapply(list_vals, pmt_present)
  13. #create df of results
  14. present_df <- as.data.frame(cbind(list_vals, present_list))

请注意,我只翻译了代码部分,没有包括问题部分的翻译。

英文:

What is the fastest way to check if values in a list are in a dataframe?

Here is what I have tried (on a much larger dataset with a much larger list)

  1. #list
  2. list_vals &lt;- list(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;)
  3. #dataframe
  4. df &lt;- data.frame(col1 &lt;- c(&quot;1&quot;, &quot;a&quot;, &quot;c&quot;),
  5. col2 &lt;- c(&quot;24a&quot; , &quot;d&quot;, &quot;b&quot;))
  6. #function to check presence
  7. pmt_present &lt;- function(x) {
  8. present &lt;- any(df==x)
  9. return(present)
  10. }
  11. #run check for vals in df
  12. present_list &lt;- lapply(list_vals, pmt_present)
  13. #create df of results
  14. present_df &lt;- as.data.frame(cbind(list_vals, present_list))

My code was running all night and when I stopped it it threw this error

Error in base::try(sample_long_mutate, silent = TRUE) : object &#39;sample_long_mutate&#39; not found

But it works perfectly in the small example.

答案1

得分: 4

使用 %in%unlist

  1. > unlist(list_vals) %in% unlist(df)
  2. [1] TRUE TRUE TRUE TRUE
英文:

Use %in% along with unlist

  1. &gt; unlist(list_vals) %in% unlist(df)
  2. [1] TRUE TRUE TRUE TRUE

答案2

得分: 2

  1. list_vals %in% t(df)
  2. [1] TRUE TRUE TRUE TRUE
英文:

Or may also do

  1. list_vals %in% t(df)
  2. [1] TRUE TRUE TRUE TRUE

huangapple
  • 本文由 发表于 2023年3月3日 21:56:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627986.html
匿名

发表评论

匿名网友

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

确定