Home > database >  Turn a character string into a numeric vector
Turn a character string into a numeric vector

Time:09-23

I have a large data table, that contains tri-axial raw accelerometer data. So I have a column with the timestamp in POSIXct format, and three columns acc_x, acc_y and acc_z for the acceleration. The data has measurements from a 20Hz accelerometer and lasts 2s, so each entry is a character string of 40 different values. For example:

> dt$acc_x[1]
[1] "44 -163 191 -240 101 369 -11 17 348 63 156 301 -126 3 -17 307 -205 320 -72 414 -173 158 528 -150 25 101 266 -193 246 212 593 73 221 580 -51 262 151 405 -25 356"

I want to find a way to split the character string to its numeric values and store it as a vector. Would that be possible?

Edit 1: I realized that I phrased that in the wrong way, but I am trying to understand if I can store the vector where the character string is.

CodePudding user response:

Just use strsplit() along with a numeric cast:

x <- "44 -163 191 -240 101 369 -11 17 348 63 156 301 -126 3 -17 307 -205 320 -72 414 -173 158 528 -150 25 101 266 -193 246 212 593 73 221 580 -51 262 151 405 -25 356"
nums <- as.numeric(strsplit(x, " ")[[1]])
nums

 [1]   44 -163  191 -240  101  369  -11   17  348   63  156  301 -126    3  -17
[16]  307 -205  320  -72  414 -173  158  528 -150   25  101  266 -193  246  212
[31]  593   73  221  580  -51  262  151  405  -25  356

CodePudding user response:

You can use scan

scan(
  text = "44 -163 191 -240 101 369 -11 17 348 63 156 301 -126 3 -17 307 -205 320 -72 414 -173 158 528 -150 25 101 266 -193 246 212 593 73 221 580 -51 262 151 405 -25 356", 
  what = 0, 
  quiet = TRUE
)

and you will obtain a numeric vector

 [1]   44 -163  191 -240  101  369  -11   17  348   63  156  301 -126    3  -17
[16]  307 -205  320  -72  414 -173  158  528 -150   25  101  266 -193  246  212
[31]  593   73  221  580  -51  262  151  405  -25  356
  • Related