R – iteratively changing column classes

[This article was first published on R – scottishsnow, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
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"
}

To leave a comment for the author, please follow the link and comment on their blog: R – scottishsnow.

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.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)