I am trying to turn a nested list structure into a dataframe. The list looks similar to the following (it is serialized data from parsed JSON read in using the httr package)
If you just want to convert all-numeric vectors that have been erroneously classed as character when they were read in, you can also use the function all.is.numeric
from the Hmisc
package:
myDF2 <- lapply(myDF, Hmisc::all.is.numeric, what = "vector", extras = NA)
Choosing what = "vector"
will convert the vector to numeric if it only contains numbers. NAs or other types of missing values will prevent conversion unless they are specified in the extras
argument as above.
Note however that if applied to a whole data.frame containing Date or POSIXct vectors, these will also be converted to numeric. To prevent this you can wrap it in a function as below:
catchNumeric <- function(dtcol) {
require(Hmisc)
if (is.character(dtcol)) {
dtcol1 = all.is.numeric(dtcol, what = "vector", extras = NA)
} else {
dtcol1 = dtcol
}
return(dtcol1)
}
Then apply to your data.frame:
myDF2 <- lapply(myDF, catchNumeric)