# Dealing with different object types in a vector in R

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**We think therefore we R**, 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.

I came across a little problem while dealing with a vector in R which had one of the most simple solutions. These are, in my opinion, the most annoying problems with the most simple and commonsensical solution. Anyways, yet again Utkarsh comes to rescue and slaps me with the realization that no matter what one does nothing can match an open mind and common sense.Well, I hope someone struggling with a similar problem might bump into this post and might save him/her some frustration and time.

**Problem**:

How to deal with different object types in one vector.

**Example:**

> testdata <- data.frame(id = c(1:5), x = c(1,2,3,NA,"Shre")) > testdata id x 1 1 1 2 2 2 3 3 3 4 45 5 Shre

Here we have a data frame “testdata” where we have a variable “x” which say is supposed to be numeric but due to that funny entry “Shre” in the 5th row, the variable becomes a “factor”.

> sapply(testdata[1,],class) id x "integer" "factor"

Now, if I try to convert the the variable “x” to numeric using as.numeric() this is what happens.

> testdata$x <- as.numeric(testdata$x) > testdata$x [1] 1 2 3 NA 4

R understands “x” to be a factor and tries to coerce it to a numeric,

**which is a common mistake that I make in data analysis**. This does not throw any error which makes it all the more difficult to detect/debug. Treating “x” to be factor the new value “Shre” is treated as the 4th category of the factor and is assigned numeric value “4” which is not what you want.**Solution:**

So an elegant way of dealing with this is:

> testdata$x <- as.numeric(as.character(testdata$x)) Warning message: NAs introduced by coercion > testdata$x [1] 1 2 3 NA NA

Tada! We have coerced “NA’s” but at least we do not have a random value “4” assigned to an observation.

To

**leave a comment**for the author, please follow the link and comment on their blog:**We think therefore we R**.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.