gpt4 book ai didi

r - 如何在具有分类变量的数据框的一行内进行排序?

转载 作者:行者123 更新时间:2023-12-05 03:30:37 26 4
gpt4 key购买 nike

我有这个代码:

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))
<表类="s-表"><头>claim1claim2claim3claim4time1time2time3time4<正文>导数导数类类28110导数导数类类5439

我正在寻找在以下输出中得到它的排序:

<表类="s-表"><头>claim1claim2claim3claim4time1time2time3time4<正文>类导数导数类12810类导数导数类3459

我试图在一行中进行排序,但我不确定如何将声明和时间链接在一起。我猜字典在这里不起作用,因为它是一个数组。

最佳答案

对于长数据,这肯定容易得多,因此,至少在 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

关于r - 如何在具有分类变量的数据框的一行内进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70788259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com