问题描述
限时送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
,替换u
和 e-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:关键词]
发布评论