英文:
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 <- 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))
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 'sample_long_mutate' 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
> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论