R – iteratively changing column classes
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
When you write an ESRI Shapefile from R, writeOGR assumes your numeric fields are real numbers and so you get a lot of redundant zeros appended. This is misleading and distracting when you present data to third parties. You can fix this by changing column class from numeric to integer:
class(df$col) = "integer"
However, this only changes one column at a time. You can’t change the whole data frame (S4 spatial, or whatever) using the same method, or you’ll no longer have a data frame. Usually I’d solve this problem using an *apply method, in this case mapply or apply, but these don’t work in this case because the data frame is coerced into a matrix. This is one of the rare occasions when you need to use a for loop in R:
cols_to_change = c(1, 3, 5:9) for(i in cols_to_change){ class(df[, i]) = "integer" }
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.