[R] convert character vector to decimal for numeric testing
Luigi Marongiu
marongiu.luigi at gmail.com
Wed Jul 15 12:26:12 CEST 2015
Dear all,
I have a vector that comes from some calculations I am making and this
vectors turns out to be in character format rather than numerical. I
can convert it in numerical format but then the calculations are not
correct, as you can see in the following example. I was also expecting
that rounding a number such as 5.43 to a three digits one would return
5.430 but that did not happen. Any tips on how to apply the
calculation correctly?
Thank you
best regards
luigi
>>>
vec.ori <- c("5.43", "6.63", "-1.18593063116494e+36", "6.2", "5.61",
"4.96842801255869e+30", "5.59", "-Inf", "Inf", "5.49", "18.35",
"-3.11", "6.07", NA)
vec.num <- as.numeric(vec.ori)
vec.num <0
[1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE
TRUE FALSE NA
vec.num >0
[1] TRUE TRUE FALSE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE
FALSE TRUE NA
for(i in 1:length(vec.num)) {
cat("value at beginning: ", vec.num[i], "\n", sep="")
if(vec.num[i] < 0) {
vec.num[i] <- "LO"
} else if(vec.num[i] > 45) {
vec.num[i] <- "HI"
} else if (is.na(vec.num[i])== TRUE) {
vec.num[i] <- "na"
} else if (is.infinite(vec.num[i]) == TRUE) {
vec.num[i] <- "INF"
} else {
vec.num[i] <- round(vec.num[i], 3)
}
cat("value at end: ", vec.num[i], "\n", sep="")
}
value at beginning: 5.43
value at end: 5.43
value at beginning: 6.63
value at end: 6.63
value at beginning: -1185930631164940020264024442864400022
value at end: LO # REM: error!
value at beginning: 6.2
value at end: HI # REM: error!
value at beginning: 5.61
value at end: HI # REM: error!
value at beginning: 4968428012558689723622822000404
value at end: HI
value at beginning: 5.59
value at end: HI # REM: error!
value at beginning: -Inf
value at end: LO # REM: error!
value at beginning: Inf
value at end: HI # REM: error!
value at beginning: 5.49
value at end: HI # REM: error!
value at beginning: 18.35
Error in round(vec.num[i], 3) :
non-numeric argument to mathematical function
# REM: cycle crashed
More information about the R-help
mailing list