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

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

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

问题

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

#list
list_vals <- list("a", "b", "c", "d")

#dataframe
df <- data.frame(col1 <- c("1", "a", "c"),
                 col2 <- c("24a", "d", "b"))

#function to check presence 
pmt_present <- function(x) {
  present <- any(df==x)
  return(present)
}

#run check for vals in df
present_list <- lapply(list_vals, pmt_present)

#create df of results
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)

#list
list_vals &lt;- list(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;)

#dataframe
df &lt;- data.frame(col1 &lt;- c(&quot;1&quot;, &quot;a&quot;, &quot;c&quot;),
                 col2 &lt;- c(&quot;24a&quot; , &quot;d&quot;, &quot;b&quot;))

#function to check presence 
pmt_present &lt;- function(x) {
  present &lt;- any(df==x)
  return(present)
}

#run check for vals in df
present_list &lt;- lapply(list_vals, pmt_present)

#create df of results
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

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

Use %in% along with unlist

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

答案2

得分: 2

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

Or may also do

list_vals %in% t(df)
[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:

确定