Home > other >  I need to verify that a variable exists in a database. Shiny in R
I need to verify that a variable exists in a database. Shiny in R

Time:05-07

I have a query that gives me a dataframe. When I receive the data frame, I use this code to make some numeric variables:

variables_numeric<-c("A","B","C","D")
datos[, variables_numeric] <- lapply(datos[, variables_numeric], as.numeric)

But when for some reason one of these columns does not come in the df, I get this error:

Warning: Error in [.data.frame: undefined columns selected

There is some way to avoid this? I was thinking in use ifelse to check first if the dataframe countain the variable.

CodePudding user response:

Maybe you can first find the variables in datos and then apply your code logic:

datos <- data.frame(A = 1, B = 2, C = 3)
variables_numeric <- c("A","B","C","D")
variables_in_df <- variables_numeric[variables_numeric %in% names(datos)]

datos[, variables_in_df] <- lapply(datos[, variables_in_df], as.numeric)
  • Related