将具有时间单位(ms、s、us)的字符转换为数字

编程入门 行业动态 更新时间:2024-10-28 20:24:22
本文介绍了将具有时间单位(ms、s、us)的字符转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的数据框中的一列是一个字符向量,其时间跨度值表示为数字+后缀,如下所示:

One of the columns in my data frame is a character vector with time span values represented as number+suffix, as so:

c("16.14ms", "7.58ms", "8.38ms", "7.29ms", "6.40ms", "5.76ms", 
"5.56ms", "5.27us", "5.12ms", "5.03us", "4.91ms", "4.76ms", "16.12ms", 
"7.56ms", "8.59ms", "7.16ms", "6.59ms", "5.91s", "5.62ms", "5.44ms"
)

单位限制为微us、毫ms和完整秒s.

The units are limited to micro us, milli ms, and full seconds s.

有没有一种简单的方法可以将它变成一个所有值都以毫秒或秒为单位的数字列?

Is there a simple way to make this into a numeric column with all values being either in milliseconds or seconds?

推荐答案

这里有一些方法.我们假设 x 是问题中显示的输入向量.

Here are some approaches. We suppose x is the input vector shown in the question.

1) 去掉s,用e-3替换m,替换ue-6.然后转换为数字:

1) Remove the s, replace m with e-3 and replace u with e-6. Then convert to numeric:

as.numeric(sub("u", "e-6", sub("m", "e-3", sub("s", "", x))))

2) 这也可以使用 gsubfn 巧妙地完成.首先我们匹配后缀,然后使用替换列表,如下所示:

2) This could also be done neatly using gsubfn. First we match the suffix and then use a replacement list as shown:

library(gsubfn)

as.numeric(gsubfn("\\D+$", list(ms = "e-3", us = "e-6", s = "e0"), x))

如果希望将问题扩展到多个时间单位,这将特别方便,因为这只是扩展列表的问题.

This would be particularly convenient if it were desired to extend the problem to many time units as it would just be a matter of extending the list.

请注意,在 gsubfn 小插图的第 4 页顶部有一个与此非常接近的示例.

Note that at the top of page 4 of the gsubfn vignette there is an example which is very close to this one.

这篇关于将具有时间单位(ms、s、us)的字符转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 12:25:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393497.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符   单位   数字   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!