我有這個代碼:
test <- data.frame("ClaimType1" = "Derivative", "ClaimType2" = "Derivative","ClaimType3" = "Class", "ClaimType4" = "Class", "Time1" = c(2,5), "Time2" = c(8,4), "Time3" = c(1,3), "Time4" = c(10,9))
| 索賠1 | 索賠2 | 索賠3 | 索賠4 | 時間1 | 時間2 | 時間3 | 時間4 |
|---|---|---|---|---|---|---|---|
| 衍生物 | 衍生物 | 班級 | 班級 | 2 | 8 | 1 | 10 |
| 衍生物 | 衍生物 | 班級 | 班級 | 5 | 4 | 3 | 9 |
我正在尋找在以下輸出中對它進行排序:
| 索賠1 | 索賠2 | 索賠3 | 索賠4 | 時間1 | 時間2 | 時間3 | 時間4 |
|---|---|---|---|---|---|---|---|
| 班級 | 衍生物 | 衍生物 | 班級 | 1 | 2 | 8 | 10 |
| 班級 | 衍生物 | 衍生物 | 班級 | 3 | 4 | 5 | 9 |
我正在嘗試連續排序,但我不確定如何將索賠和時間聯系在一起。我猜字典在這里不起作用,因為它是一個陣列。
uj5u.com熱心網友回復:
由于您希望切斷基于列的關系,我建議使用拆分-應用-組合型別的作業流。這個想法是將資料框分成更小的部分,以您想要的方式對每個部分進行操作,然后將它們重新粘合在一起。
使用baseR 和一些極其不雅的代碼來展示這個想法:
helper_function <- function(x){
time_rank <- order(as.numeric(x[5:8]))
c(x[time_rank], x[time_rank 4])
}
as.data.frame(t(apply(test, 1, helper_function)))
## V1 V2 V3 V4 V5 V6 V7 V8
## 1 Class Derivative Derivative Class 1 2 8 10
## 2 Class Derivative Derivative Class 3 4 5 9
關鍵思想是用來order()寫下您希望每一行排列的方式;然后,您可以將該排列應用于每行的多個部分。
現在,我們應該清理它,因為我們已經銷毀了列名和型別:
test_output <- as.data.frame(t(apply(test, 1, helper_function)))
colnames(test_output) <- c("claim1", "claim2", "claim3", "claim4",
"test1", "test2", "test3", "test4")
test_output[5:8] <- apply(test_output[, 5:8], 2, as.numeric)
test_output
## claim1 claim2 claim3 claim4 test1 test2 test3 test4
## 1 Class Derivative Derivative Class 1 2 8 10
## 2 Class Derivative Derivative Class 3 4 5 9
str(test_output)
我會提到,5:8像我多次提到的那樣參考靜態列號(例如 )并不是很好的做法,但希望這可以傳達一種可能的方法。
uj5u.com熱心網友回復:
對于長資料,這肯定要容易得多,因此,至少在 中dplyr,必須先進行 pivot_longer 然后將 pivot_wider 回傳:
library(dplyr)
library(tidyr)
test %>%
pivot_longer(cols = everything(), names_to = c(".value","col"), names_pattern = "(ClaimType|Time)(.*)") %>%
mutate(group = cumsum(col == 1)) %>%
arrange(group, Time, .by_group = T) %>%
mutate(col = sequence(rle(group)$l)) %>%
pivot_wider(id_cols = group, names_from = col, values_from = c("ClaimType","Time"), names_sep = "") %>%
select(-group)
ClaimType1 ClaimType2 ClaimType3 ClaimType4 Time1 Time2 Time3 Time4
<chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 Class Derivative Derivative Class 1 2 8 10
2 Class Derivative Derivative Class 3 4 5 9
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/417305.html
標籤:
