【问题标题】:How to convert typeof "character" to typeof "integer" and parsed into either a matrix or a data.frame, in R [closed]如何在 R [关闭] 中将 typeof“字符”转换为 typeof“整数”并解析为矩阵或 data.frame
【发布时间】:2016-09-21 19:52:45
【问题描述】:

将数据从 typeof "character" 转换为 typeof "integer" 并解析为矩阵或 data.frame 并保留顺序的最佳方法是什么?

我正在使用 r 串行包 (from CRAN) 使用包中提供的示例将数据从串行端口获取到 R。输出是 typeof "character" (请参阅这个问题 "How to Read Data from Serial Port in R"),但我希望它是 typeof 整数,并且在矩阵或 data.frame 中。

我的数据如下所示:

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

我想把上面的改成:[6, 3]

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

背景: 数据来自三个振动开关(快、中、慢),值是自开关最后一次操作以来的微秒数。振动开关连接到ESP8266,然后通过 USB 端口发送数据,然后通过 Wifi。该装置已(或将)连接到我的洗衣机,让我知道它处于循环的哪个阶段,或者它是否失去平衡并停止。

请注意:如果可能,我希望读取串口的功能尽可能简单。我是 R 新手,我很想写出好的代码。

【问题讨论】:

  • data.table::fread(foo2)
  • 如果你澄清你对 typeof() 函数的意思可能会有所帮助,因为 "vector" 不是函数会返回的东西之一,我不认为。
  • 不确定我明白你想要什么。也许像df1 <- read.table(text=foo) 这样的东西会有所帮助。
  • joran,感谢您编辑问题的格式,但请让我知道您做了什么,以便我下次有更好的机会做对:-) 而且您对 typeof( ),我希望将数据更改为整数。如果还有其他问题,请告诉我。

标签: r parsing serial-port integer character


【解决方案1】:

我认为您错误地提出了您的问题,因为您想要的是矩阵或 data.frame。你想要的不是转换而是解析。您可以使用 read.table 或类似函数读取字符串,就像您可以使用以下命令读取文件一样:

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 的回答之外,以下 cmets 也提供了很好的回答:HubertL 的 "data.table::fread(foo2)" "df1
猜你喜欢
  • 2015-08-06
  • 1970-01-01
  • 2017-12-22
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2017-08-12
  • 1970-01-01
相关资源
最近更新 更多