'How to convert a character to a numeric data type in R [closed]
I have a big .csv file and one of the columns "ride_id" is a character type. I would like to convert it to numeric type but I get NA values.
ride_id
<chr>
3ED2B8BCE6A914EF
7359345F8EB21CDC
A62608C1D9DF9360
20D609100DF8A71C
6DF34F98F5DB335F
E3194C33D112E064
I try using this code and it doesnt work:
ride_id = as.numeric(ride_id)
The reason I would like to convert the data type is to calculate the total into a separate column. This would then be used as a y variable in a geom_line.
Any suggestions?
Solution 1:[1]
Here are two possibilities.
1) type.convert
transform(ride_id, num = type.convert(paste0("0x", chr), as.is = TRUE))
giving:
chr num
1 3ED2B8BCE6A914EF 4.526884e+18
2 7359345F8EB21CDC 8.311732e+18
3 A62608C1D9DF9360 1.197227e+19
4 20D609100DF8A71C 2.366089e+18
5 6DF34F98F5DB335F 7.922764e+18
6 E3194C33D112E064 1.636419e+19
2) strotoi Break the character string up into 4 strings of 4 characters each, convert those using strtoi (which can only work on sufficiently short strings) and then matrix multiply that by the indicated vector.
transform(ride_id, num = chr |>
textConnection() |>
read.fwf(c(4, 4, 4, 4)) |>
apply(2, strtoi, base = 16) |>
t() |>
crossprod(cbind((16^4)^(3:0))))
giving:
chr num
1 3ED2B8BCE6A914EF 4.526884e+18
2 7359345F8EB21CDC 8.311732e+18
3 A62608C1D9DF9360 1.197227e+19
4 20D609100DF8A71C 2.366089e+18
5 6DF34F98F5DB335F 7.922764e+18
6 E3194C33D112E064 1.636419e+19
Note
Lines <- "chr
3ED2B8BCE6A914EF
7359345F8EB21CDC
A62608C1D9DF9360
20D609100DF8A71C
6DF34F98F5DB335F
E3194C33D112E064"
ride_id <- read.table(text = Lines, header = TRUE)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | G. Grothendieck |
