-3

What is the best way to convert data from typeof "character" to typeof "integer" and parsed into either a matrix or a data.frame, preserving the order?

I'm using the r serial package (from CRAN) to get data from a serial port into R, using the example provided in the package. The output is typeof "character" (Please see this question "How to Read Data from Serial Port in R"), but I would like it to be typeof integer, and in either a matrix or a data.frame.

My data looks like this:

 > foo
[2] " 36037960 0 0\n100 0 0\n35 0 0\n33 0 0\n33 0 0\n0 36077681 0"
 >

I would like to change the above to: [6, 3]

36037960    0   0
100 0   0
35  0   0
33  0   0
33  0   0
0   36077681 0

Background: The data is from three vibration switches (fast, medium, slow), and the value is the number of microseconds since the switch last operated. The vibration switches are attached to an ESP8266, this then sends the data via the USB port, and later by Wifi. This unit is (or will be) attached to my washing machine, to let me know at what stage of the cycle it is at, or if it is out of balance and stopped.

Please note: If possible, I wish to keep the function that reads the serial port as simple as possible. I am new to R and I'm keen to write good code.

Community
  • 1
  • 1
Geoff
  • 3
  • 3
  • `data.table::fread(foo2)` – HubertL Sep 21 '16 at 19:56
  • 3
    It might help if you clarified what you mean about the `typeof()` function, because `"vector"` is not one of the things that function will return, I don't think. – joran Sep 21 '16 at 19:57
  • 2
    Not sure I understand what you want. Maybe something like `df1 <- read.table(text=foo)` could help. – RHertel Sep 21 '16 at 19:58
  • joran, thank your for editing the format of the question but please let me know what you did so I stand a better chance of getting it right next time:-) And you are right about the typeof(), I was looking to change the data to an integer. Please let me know if there is anything else. – Geoff Sep 22 '16 at 20:16

1 Answers1

1

I think you formulated your question wrongly as what you want is either a matrix or a data.frame. And what you want isn't conversion but parsing. You can read strings with read.table or similar functions just like you can read files with:

read.table(textConnection(foo))

        V1       V2 V3
1 36037960        0  0
2      100        0  0
3       35        0  0
4       33        0  0
5       33        0  0
6        0 36077681  0
OganM
  • 2,543
  • 16
  • 33
  • Thank you, I'll edit the question. – Geoff Sep 22 '16 at 20:19
  • Thank you to all who responded to this question :-) As well as OganM's answer, the following comments also provide good answers: "data.table::fread(foo2)" by HubertL "df1 <- read.table(text=foo)" by RHertel The comments and answer has provided me with good guidance as to what to study, Thank you :-) – Geoff Oct 02 '16 at 16:12