trob
trob

Reputation: 1

converting a chr into num in R

I have some data that is currently in character form, and I need to put it into numeric form so that I can get the mean. I'm new to R so any help will be much appreciated. My initial thought was that the missing data is causing it to not be read as num, but could it be because the numbers are "3" instead of 3?

Here's what I have:

X
chr [1:1964] "3", "4", "4", "1", NA

I've tried different methods of converting X from chr to num:


X <- na.omit(Y, Z, as.numeric)
mean(X)
# [1] NA
# Warning message:
# In mean.default(X) :
#  argument is not numeric or logical: returning NA

X <- c(Y, Z, na.rm=TRUE)
mean(X, na.rm=TRUE)
# [1] NA
# Warning message:
# In mean.default(X, na.rm = TRUE) :
#   argument is not numeric or logical: returning NA

X <- c(Y, Z, na.rm=TRUE)
str(X)
#  Named chr [1:1965] "3" "4" "4" "1" "5" "7" NA "6" NA "5" ...
#  - attr(*, "names")= chr [1:1965] "" "" "" "" ...

Upvotes: 0

Views: 5226

Answers (2)

MrFlick
MrFlick

Reputation: 206546

This should work:

mean(as.numeric(X), na.rm=TRUE)

Doing the as.numeric() will introduce an NA for values like "X" and many of the summary functions have a na.rm parameter to ignore NA values in the vector.

But of course taking the mean of a list of chromosomes is a pretty weird operation.

Upvotes: 0

shirewoman2
shirewoman2

Reputation: 1950

As always, an example of your actual data is helpful. I think I can answer anyway, though. If your data are character data, then converting to numeric like this will work most of the time:

 X2 <- as.numeric(X)

If you have missing values, are they showing up as NA? Or did you write something else there to indicate missingness such as "missing"? If you've got something other than NA in your original data, then when you do the as.numeric(X) conversion, R will convert those values to NA and give you a warning message.

To take the mean of a numeric object that has missing values, use:

 mean(X2, na.rm=TRUE)

Upvotes: 1

Related Questions