【发布时间】:2022-01-22 08:57:53
【问题描述】:
我在使用 datas 中的 pivot_longer 函数时遇到问题。你能帮我解决吗?
在这个问题中正常工作:How to adjust error when I have 0 values for graph generation。但是,在上一个问题中,我没有使用DTT 列,在当前问题中是。
library(dplyr)
df1 <- structure(
list(date1= c("2021-06-28","2021-06-28","2021-06-28"),
date2 = c("2021-06-30","2021-06-30","2021-07-02"),
DTT= c(NA,NA,"Hol"),
Week= c("Wednesday","Wednesday","Friday"),
Category = c("ABC","FDE","ABC"),
DR1 = c(4,1,0),
DR01 = c(4,1,0), DR02= c(4,2,0),DR03= c(9,5,0),
DR04 = c(5,4,0),DR05 = c(5,4,0)),
class = "data.frame", row.names = c(NA, -3L))
dmda<-"2021-07-02"
CategoryChosse<-"ABC"
DTest<-"Hol"
x<-df1 %>% select(starts_with("DR0"))
x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
PV<-select(x, date2,Week, Category, DTT, DR1, ends_with("PV"))
med<-PV %>%
group_by(Category,Week,DTT) %>%
summarize(across(ends_with("PV"), median))
SPV<-df1%>%
inner_join(med, by = c('Category', 'Week','DTT')) %>%
mutate(across(matches("^DR0\\d+$"), ~.x +
get(paste0(cur_column(), '_PV')),
.names = '{col}_{col}_PV')) %>%
select(date1:Category, DR01_DR01_PV:last_col())
SPV<-data.frame(SPV)
mat1 <- df1 %>%
filter(date2 == dmda, Category == CategoryChosse, DTT==DTest) %>%
select(starts_with("DR0")) %>%
pivot_longer(cols = everything()) %>%
arrange(desc(row_number())) %>%
mutate(cs = cumsum(value)) %>%
filter(cs == 0) %>%
pull(name)
(dropnames <- paste0(mat1,"_",mat1, "_PV"))
SPV <- SPV %>%
filter(date2 == dmda, Category == CategoryChosse, DTT==DTest) %>%
select(-any_of(dropnames))
if(length(grep("DR0", names(SPV))) == 0) {
SPV[mat1] <- NA_real_
}
datas <-SPV %>%
filter(date2 == ymd(dmda)) %>%
group_by(Category, DTT) %>%
summarize(across(starts_with("DR0"), sum)) %>%
pivot_longer(cols= -Category, names_pattern = "DR0(.+)", values_to = "val") %>%
mutate(name = readr::parse_number(name))
colnames(datas)[-1]<-c("Days","Numbers")
Error: Can't combine `DTT` <character> and `DR05` <double>.
Run `rlang::last_error()` to see where the error occurred.
【问题讨论】:
-
我认为在
pivot_longer中,您只需要包含“DRO”列,因为-Category暗示所有其他列,并且有DTT这是字符即`pivot_longer(cols= starts_with("DR0"), names_pattern = "DR0(.+)",跨度> -
就是这样,非常感谢akrun!您可以以答案的形式留下它以便我接受吗?此外,我还有两个问题:
colnames更改后会是什么样子?如果我的DTT是NA,则喜欢DTest。是DTest = ""还是DTest = NA还是DTest = "NA"? -
我发布了一个解决方案。请检查
-
是的,就是这样。关于我关于 DTest 的第二个问题?如果
DTT是NA,它会是什么样子?例如,对于 30/06,类别 ABC -
让我测试一下