'I need to verify that a variable exists in a database. Shiny in R
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.
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Douglas Mesquita |
