英文:
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('(\\d+):(\\d+).*', '\.\', x))
# [1] 8.40 18.41 0.00
Data:
x <- c('08:40:01', '18:41:01', '00:00:01')
答案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 <- as.numeric(chartr(":", ".",
sub(":\\d{2}$", "", Camera_data$Numeric_time )))
Or use substr
Camera_data$Numeric_time <- substr(Camera_data$Numeric_time, 1, nchar(Camera_data$Numeric_time)-3)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论