Tips & Tricks 4: Reading In Data Files

[This article was first published on geomorph, 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.

Today’s exercise is another nice and simple one, and allows you to get used to manipulating datasets in R.

Exercise 4 – How to read a file of coordinate data into R and make sure it is numeric.

Reading your data files into R  for analysis with geomorph or other packages can be challenging. Geomorph has several functions for common data file types of coordinate data (e.g. readland.tps(), readland.nts()).

But what if your data are not in this format?

One of the main issues people face is that using read.table() or read.delim(), numerical data can be coerced into a factor automatically. Below is a very simple solution to make sure your data are numerical:

mydata <- read.table("data.txt",header=TRUE,row.names=1,
stringsAsFactors = FALSE) 
# here we are reading in a tab-delimited text file from MorphoJ, but this can be an issue with data from any outside program. The stringsAsFactors = FALSE is VERY important here

is.numeric(mydata)
[1] FALSE # here R tells is the data are not numeric, even though we can see they are if we use View(mydata).

The solution is:
as.matrix(sapply(mydata[], as.numeric))

For example, say we know the shape coordinates are present in the file after two columns of non-shape coordinates (these could be centroid size, or a classifier), then:

shape <- as.matrix(sapply(mydata[,-(1:2)], as.numeric)) 
# here we say, use all columns except the first two.

is.numeric(shape)
[1] TRUE # now it’s numeric. Ready to go!

Simple! 

Emma

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

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)