我有一个数据框,其中的一栏代表被称为num_days的天数,即“ 0”,“'',“ 0xY0xM”,“ 0xM”,我想将其更改为天数。
这就是数据框的样子
| a | b | num_days | d |
| 2 | 3 | '01Y' | 99 |
| 2 | 4 | "" | 8 |
| 3 | 7 | "01Y02M" | 7 |
| 4 | 1 | "0" | 8 |
每年Y代表365天,每个月代表30天
| a | b | num_days | d |
| 2 | 3 | 365 | 99 |
| 2 | 4 | 0 | 8 |
| 3 | 7 | 425 | 7 |
| 4 | 1 | 0 | 8 |
目前这是解决方案:
return_days <- function(x){
if(x == ""){
return(0)
}
d = gsub("Y", ".", x=x, ignore.case=FALSE, fixed=TRUE)
d = gsub("M", "" , x=d, ignore.case=FALSE, fixed=TRUE)
d = strsplit(d, '[.]')
return( ifelse(length(d[[1]]) == 1, 30*as.numeric(x[[1]][1]), 30* as.numeric(d[[1]][1]) + 365*as.numeric(d[[1]][2]) ) )
}
我确信这可以写得更好,但是不幸的是我还不是R向导。任何帮助表示赞赏。谢谢
一个选择是 gsubfn
library(gsubfn)
i1 <- !df1$num_days %in% c("", 0)
df1$num_days[i1] <-sapply(gsub("\\+$", "", gsubfn("[A-Z]",
list(Y= '*365+', M = '*30'),
df1$num_days[i1])), function(x) eval(parse(text = x)))
或使用 tidyverse
library(tidyverse)
df1 %>%
mutate(num_days = case_when(str_detect(num_days, "Y|M") ~
as.numeric(str_extract(num_days, "\\d+(?=Y)") ) * 365 +
replace_na(as.numeric(str_extract(num_days, "\\d+(?=M)")) * 30, 0),
TRUE ~ as.numeric(num_days) ))
df1 <- structure(list(a = c(2L, 2L, 3L, 4L), b = c(3L, 4L, 7L, 1L),
num_days = c("01Y", "", "01Y02M", "0"), d = c(99L, 8L, 7L,
8L)), class = "data.frame", row.names = c(NA, -4L))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句