我有一个类似于以下reprex的数据框:
test <- data.frame(
age = c("6 hours", "2 days, 4 hours", "1 months3 days, 7 hours")
)
不幸的是,正如您在第 3 行中看到的那样,字符串的三个部分并非全部用逗号分隔。
我的预期输出如下:
age agem aged ageh
1 6 hours NA NA 6
2 2 days, 4 hours NA 2 4
3 1 months3 days, 7 hours 1 3 7
我试过使用这样的dplyr::separate
new_test <- test %>%
separate(age, c("agem", "ageh", "aged"), sep = "[^[\d]]+", convert = TRUE,
remove = FALSE, fill = "left")
这适用于只有"小时"的条目,但如果有"天和小时"或"月、日和小时",则输出的顺序是错误的。
任何帮助将不胜感激。
您可以使用包中的str_extract
stringr
和积极的展望(?= ...)
:
test$agem <- str_extract(test$age, "\d+(?=\smonth)")
test$aged <- str_extract(test$age, "\d+(?=\sday)")
test$ageh <- str_extract(test$age, "\d+(?=\shour)")
结果:
test
age agem aged ageh
1 6 hours <NA> <NA> 6
2 2 days, 4 hours <NA> 2 4
3 1 months3 days, 7 hours 1 3 7
首先,在字母字符和数字之间没有分隔符的地方包含一个分隔符。然后tidyr::separate
成列。
library(tidyverse)
test %>%
mutate(age = gsub("([[:alpha:]])([[:digit:]])", "\1, \2", age)) %>%
separate(age, into = c('agem', 'aged', 'ageh'),
sep = ', ',
convert = TRUE,
remove = FALSE, fill = "left") %>%
mutate_at(vars(matches('age[[:alpha:]]')), function(x) as.numeric(gsub('[^[:digit:]]', '', x)))
# age agem aged ageh
#1 6 hours NA NA 6
#2 2 days, 4 hours NA 2 4
#3 1 months, 3 days, 7 hours 1 3 7