I'm trying to preserve all information (decimal points) and turn all of the vectors into numeric. So far I've tried turning these vectors into characters and then to numeric, which was suggested in SO but I get
which does not preserve all the decimal points, and does not fill in the blank as NAs. I've also tried
> gdp<-as.numeric(levels(gdp))[gdp]
Error in as.numeric(levels(gdp))[gdp] : invalid subscript type 'list'
Will there be a way to turn the vectors into numeric?
La solution
Let's break this down.
First, because gdp is a data frame, levels will return NULL. You may be looking for the output of levels on each column of gdp. In which case you'd want to use something like lapply.
levels(gdp)
# NULL
lapply(gdp, levels)
# this output will make sense
as.numeric(levels(gdp))[gdp]
# this will make no sense
The error is stating that you cannot use a list (gdp) to subscript a vector.
To iterate through the columns of gdp, you will need something like lapply to work on each component.
gdp <- data.frame(lapply(gdp, function(x) {
if(!is.factor(x)) x
else as.numeric(gsub(",","",levels(x),fixed=TRUE))[x]
}))
Possibly your data set would be better served as a matrix since it appears to be all of type numeric. In which case: