Is there a way to check for matching variables names between data frames?

Viewed 60

Just started using R, so forgive me if my code/question are a bit obtuse.

I've created a list of variables names. I'd like to check if the variables in this list are present in another dataframe (lfs_ja20). Should I use a for loop, or the lapply function? Have I even created the list appropriately?

#create list of relevant variables

varlist <- tibble::lst("ACTHR","ADDJOB","AGE","AGES","AGWRK","AXFA","AXPA","BACTHR",
            "BANDG","BEFOR","BUSHR","CONMON","COUNTRY","CURED8","DIFJOB",
            "DISEA","DURUN")

#my failed attempt at a loop, which results in no error message, but yields nothing

for(i in varlist) {
  find_var(lfs_ja20,i)
}

#my failed attempt at creating a search function then using lapply, which yields the following error 
message : Error in FUN(X[[i]], ...) : argument "y" is missing, with no default

searchvar <- function(x,y) names(y[grep(x, names(y))])
lapply(varlist, searchvar)

Thank you. If there's any part of this question that is unclear, some quick advice on its framing would be helpful also.

1 Answers

if you need just to check whether column names match with elements of your list, then you can use %in% operation

Here I reproduced your example, I just used list from base and data.frame. I created sample dataframe myself because it was not provided in question

varlist <- list("ACTHR","ADDJOB","AGE","AGES","AGWRK","AXFA","AXPA","BACTHR",
                "BANDG","BEFOR","BUSHR","CONMON","COUNTRY","CURED8","DIFJOB",
                "DISEA","DURUN")
dfX <- data.frame(CURED8 = c(1,2), CONMON =c('a','b'), DURUN = c('g','t'))

Then matching gives expected result

varlist %in% names(dfX)
# names() function gets column names of dataframe

Output is

 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE
[17]  TRUE
Related