Turn a character string into a numeric vector

Viewed 39

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.

3 Answers

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

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

To store the numeric vector in-place in the original table, you can just use strsplit within the [-construct:

dt <- data.table(time = Sys.time()+0:1, acc_x = rep("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",2))
dt[, acc_x := strsplit(acc_x, " +")]
dt
#                       time                        acc_x
#                     <POSc>                       <list>
# 1: 2022-09-23 09:32:39.222 44,-163,191,-240,101,369,...
# 2: 2022-09-23 09:32:40.222 44,-163,191,-240,101,369,...

You now have a list-column, where you can reference the numbers as needed (e.g., with dt[, Map(function(x,y,z) { do_something; }, acc_x, acc_y, acc_z)]).

Related