r - Efficient Way to Convert to Numeric -


i have converted bunch of columns factor numeric, code cumbersome. had individually convert each column, ended taking more time should. code used (only short sample - have many more columns):

city1$ny <-as.numeric(levels(city1$ny))[city1$ny]    city1$chi<-as.numeric(levels(city1$chi))[city1$chi]  city1$la <-as.numeric(levels(city1$la))[city1$la]    city1$atl<-as.numeric(levels(city1$atl))[city1$atl]  city1$mia<-as.numeric(levels(city1$mia))[city1$mia] 

i positive instead of doing of that, could've done:

city1[,citynames]<-as.numeric(levels(city1[,citynames]))[city1[,citynames]] 

where citynames of columns data convert.. doesn't work, get:

error in as.numeric(levels(city1[, citynames]))[city1[, citynames]] :    invalid subscript type 'list' 

can tell doing wrong? or there no easier way task other long, annoying first method?

i positive instead of doing of that, could've done:

city1[,citynames]<-as.numeric(levels(city1[,citynames]))[city1[,citynames]] 

so, small change needed:

city1[,citynames] <- lapply(city1[,citynames], function(x) as.numeric(levels(x))[x] ) 

the original approach didn't work because

  • levels vector-specific, it's not clear myvec = levels(city1[,citynames]) is.
  • myvec[ city1[,citynames] ] throws error because city1[,citynames] data.frame , cannot used subset in way.

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -