从字符串中删除一部分并将其转换为数字?

huangapple go评论52阅读模式
英文:

Remove part of a string and turn it into a number?

问题

我有一个名为"Camera_data"的数据框和一个名为"Numeric_time"的列。

我的"Numeric_time"列是字符格式的,包括小时、分钟和秒,看起来像这样:08:40:01

我需要删除与秒相关的数字,并将分号替换为句点,以便将我的时间转换为小数,看起来像这样:08.40,以便将我的时间转换为弧度,用于我正在运行的分析。

我在stringr中寻找了一些解决方案,但迄今为止无法弄清楚如何始终删除最后三个字符。我认为一旦我去掉秒并替换:为.,我可以使用as.numeric将字符列转换为数值列,但真的很感激任何帮助!

英文:

I have a dataframe called "Camera_data" and a column called "Numeric_time"

My "Numeric_time" column is in character format and includes hours, minutes and seconds, it looks like this: 08:40:01

I need to remove the numbers that pertain to seconds and replace the semicolons with periods to make a decimal number for my time. I need it to look like this: 08.40 in order to turn my time into radians for an analysis I'm running.

I've looked for a few solutions in stringr, but so far can't work out how to consistently take off the last three characters. I think once I have removed the seconds and replaced the : with a . I can just use as.numeric to turn the character column into a numerical column, but would really appreciate any help!

答案1

得分: 1

使用带有两个捕获组的 gsub

as.numeric(gsub('(\\d+):(\\d+).*', '\.\', x))
# [1]  8.40 18.41  0.00

数据:

x <- c('08:40:01', '18:41:01', '00:00:01')
英文:

Using gsub with two capture groups.

as.numeric(gsub(&#39;(\\d+):(\\d+).*&#39;, &#39;\.\&#39;, x))
# [1]  8.40 18.41  0.00

Data:

x &lt;- c(&#39;08:40:01&#39;, &#39;18:41:01&#39;, &#39;00:00:01&#39;)

答案2

得分: 0

我们可以使用

Camera_data$Numeric_time <- as.numeric(chartr(":", ".",
sub(":\d{2}$", "", Camera_data$Numeric_time )))


或者使用 `substr`

Camera_data$Numeric_time <- substr(Camera_data$Numeric_time, 1, nchar(Camera_data$Numeric_time)-3)

英文:

We could do

Camera_data$Numeric_time &lt;- as.numeric(chartr(&quot;:&quot;, &quot;.&quot;, 
    sub(&quot;:\\d{2}$&quot;, &quot;&quot;, Camera_data$Numeric_time )))

Or use substr

Camera_data$Numeric_time &lt;- substr(Camera_data$Numeric_time, 1, nchar(Camera_data$Numeric_time)-3)

</details>



huangapple
  • 本文由 发表于 2023年2月18日 00:58:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定