【发布时间】:2021-08-18 04:51:47
【问题描述】:
让
Data_Frame <- data.frame(Col1 = c("A1", "A1", "A1", "A2", "A2", "A2", "A3", "A3", "A3"),
Col2 = c("2011-03-11", "2014-08-21", "2016-01-17", "2017-06-30", "2018-07-11", "2018-11-28", "2019-09-04", "2020-02-29", "2020-07-12"),
Col3 = c("2018-10-22", "2019-05-24", "2020-12-25", "2018-10-12", "2019-09-24", "2020-12-19", "2018-10-22", "2019-06-14", "2020-12-20"),
Col4 = c(4, 2, 2, 1, 4, 4, 4, 4, 4),
Col5 = c(7, 6, 3, 1, 3, 2, 5, 1, 2))
Data_Frame$Col2 <- as.Date(Data_Frame$Col2)
Data_Frame$Col3 <- as.Date(Data_Frame$Col3)
Data_Frame$Col1 <- as.factor(Data_Frame$Col1)
Data_Frame <- Data_Frame %>% group_by(Col1) %>% mutate(Col6 = lubridate::time_length(lubridate::interval(Col2, max(Col3)), "years"))
Data_Frame <- Data_Frame %>% group_by(Col1) %>% dplyr::mutate(Col7 = ifelse(Col6 <= 1, 1, ifelse(Col6 >1 & Col6 <=2, 2, ifelse(Col6 >2 & Col6 <=5, 5, ifelse(Col6 >5 & Col6 <=10, 10, 11)))))
Data_Frame <- as.data.frame(Data_Frame)
是数据框,其中Col6表示Col2和Col3之间的时间差,Col2的元素从Col1中A1到A3各组中Col3的最大日期元素中减去,Col7表示Col6中的哪些元素
不同条件生成的附加列存在问题。
- Last1Col7 到 Last10Col7 的生成:
新列 Last1Col7 到 Last10Col7 是基于 Col7 创建的,并且在 Col7 中将 A1 到 A3 分组,这样
- Last1Col7 表示 Col7 中有多少个元素(行数)
- Last2Col7 对应于行数
- Last5Col7 对应于每行
Data_Frame1 <- Data_Frame %>% group_by(Col1) %>% dplyr::mutate(Last1Col7 = nrow(Data_Frame[Data_Frame$Col7 <= 1, ]),
Last2Col7 = nrow(Data_Frame[Data_Frame$Col7 <= 2, ]),
Last5Col7 = nrow(Data_Frame[Data_Frame$Col7 <= 5, ]),
Last10Col7 = nrow(Data_Frame[Data_Frame$Col7 <= 10, ]))
-
Last1SumCol4Col7 到 Last10SumCol4Col7 的生成:
-
Last1SumCol4Col7 是 Col4 中的条目之和,对应于 Col1 中 A1 到 A3 的每个组中 Col7 中有多少条目(行数)
-
Last2SumCol4Col7 是 Col4 中条目的总和,对应于 Col1 中 A1 到 A3 每组中 Col7 中有多少条目(行数)
-
Last5SumCol4Col7 是 Col4 中条目的总和,对应于 Col1 中 A1 到 A3 每组中 Col7 中有多少条目(行数)
-
Last10SumCol4Col7 是 Col4 中条目的总和,对应于 Col7 中的条目(行数)在 Col1 中的 A1 到 A3 的每个组中
-
使用以下代码:
Data_Frame1 <- Data_Frame %>% group_by(Col1) %>% dplyr::mutate(Last1SumCol4Col7 = sum(Data_Frame[Data_Frame$Col7 <=1, ]$Col4),
Last2SumCol4Col7 = sum(Data_Frame[Data_Frame$Col7 <=2, ]$Col4),
Last5SumCol4Col7 = sum(Data_Frame[Data_Frame$Col7 <=5, ]$Col4),
Last10SumCol4Col7 = sum(Data_Frame[Data_Frame$Col7 <=10, ]$Col4))
从 Last1Col7 到 Last10Col7 和 Last1SumCol4Col7 到 Last10SumCol4Col7 的所有初始条目都为零的列开始,然后使用上面的代码也无济于事。 1 和 3 下的代码有什么根本性的问题?
【问题讨论】:
标签: r dataframe dplyr group-by conditional-statements