英文:
Append characters to strings in column which match expression R
问题
我有一个日期/时间列,格式不一致:
df <- data.frame(date.time=c("10-29-2022 09:46:40", "02-27-2023 22:53:53", "12-15-2022 02:54:03", "01-09-2023 14:44", "03-05-2023 14:58", "02-18-2023 19:46:35", "12-10-2022 16:50"))
我想在不包含秒的时间戳后面添加":00"(注意有些字符串比其他字符串短)。我可以使用gsub(pattern=)
找到没有秒的字符串,但是当我尝试在末尾添加":00"时,我替换了整个字符串:
df %>%
mutate_at(.vars = "date.time",
.funs = gsub,
pattern = "^\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d$",
replacement = "\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d:00")
英文:
I have a date/time column in an inconsistent format:
df <- data.frame(date.time=c("10-29-2022 09:46:40", "02-27-2023 22:53:53", "12-15-2022 02:54:03", "01-09-2023 14:44", "03-05-2023 14:58", "02-18-2023 19:46:35", "12-10-2022 16:50"))
I want to add ":00" to the time stamps that don't include seconds (notice some strings are shorter than others). I can find the strings without seconds using gsubs(pattern=) but when I try to add on ":00" to the end I'm replacing the whole string:
df %>%
mutate_at(.vars = "date.time",
.funs = gsub,
pattern = "^\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d$",
replacement = "\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d:00")
答案1
得分: 1
在这种情况下,你可以使用简单的ifelse
语句,结合nchar
和paste0
函数,而无需使用正则表达式:
df$date.time_new <- ifelse(nchar(df$date.time) < max(nchar(df$date.time)),
paste0(df$date.time, ":00"),
df$date.time)
输出结果:
date.time date.time_new
1 10-29-2022 09:46:40 10-29-2022 09:46:40
2 02-27-2023 22:53:53 02-27-2023 22:53:53
3 12-15-2022 02:54:03 12-15-2022 02:54:03
4 01-09-2023 14:44 01-09-2023 14:44:00
5 03-05-2023 14:58 03-05-2023 14:58:00
6 02-18-2023 19:46:35 02-18-2023 19:46:35
7 12-10-2022 16:50 12-10-2022 16:50:00
希望对你有帮助!
英文:
In this case, you can use a simple ifelse
with nchar
and paste0
with no need for regex:
df$date.time_new <- ifelse(nchar(df$date.time) < max(nchar(df$date.time)),
paste0(df$date.time, ":00"),
df$date.time)
Output:
date.time date.time_new
1 10-29-2022 09:46:40 10-29-2022 09:46:40
2 02-27-2023 22:53:53 02-27-2023 22:53:53
3 12-15-2022 02:54:03 12-15-2022 02:54:03
4 01-09-2023 14:44 01-09-2023 14:44:00
5 03-05-2023 14:58 03-05-2023 14:58:00
6 02-18-2023 19:46:35 02-18-2023 19:46:35
7 12-10-2022 16:50 12-10-2022 16:50:00
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论