R – iteratively changing column classes

April 4, 2017
By

(This article was first published on R – scottishsnow, and kindly contributed to R-bloggers)

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

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)