r - 如何使用 tidyverse 中使用多个变量的传播函数?

标签 r dplyr tidyverse

我正在尝试使用 tidyverse 中的传播函数来处理以下数据的不同方法,但没有成功。目的是为变量中的值的每个 id 1 和 0 提供一个新列:health、ci_high、ci_low。

id  unemployment    health  ci_high ci_low
1   5                 100   110       90
1   10                 80   90        70
1   15                 70   80        60
0   5                  90   100       80
0   10                 50   60        40
0   15                 40   50        30

structure(list(id = structure(c(1, 1, 1, 0, 0, 0), format.stata = "%9.0g"), 
    unemployment = structure(c(5, 10, 15, 5, 10, 15), format.stata = "%9.0g"), 
    health = structure(c(100, 80, 70, 90, 50, 40), format.stata = "%9.0g"), 
    ci_high = structure(c(110, 90, 80, 100, 60, 50), format.stata = "%9.0g"), 
    ci_low = structure(c(90, 70, 60, 80, 40, 30), format.stata = "%9.0g")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

我想得到这样的输出:

unemployment    health_id1  health_id0  ci_high_id1 ci_high_id0 ci_low_id1  ci_low_id0
5                    100        90            110         100        90        80
10                   80         50             90         60         70        40
15                   70         40             80         50         60        30

有人可以指导我吗?

最佳答案

使用pivot_wider

pivot_wider(df, unemployment, names_from = id, values_from = c("health", "ci_high", "ci_low"), names_prefix = "id")

# A tibble: 3 x 7
  unemployment health_id1 health_id0 ci_high_id1 ci_high_id0 ci_low_id1 ci_low_id0
         <dbl>      <dbl>      <dbl>       <dbl>       <dbl>      <dbl>      <dbl>
1            5        100         90         110         100         90         80
2           10         80         50          90          60         70         40
3           15         70         40          80          50         60         30

使用data.table

dt <- as.data.table(df)
dcast(dt, unemployment ~ id, value.var = c("health", "ci_high", "ci_low"))

   unemployment health_0 health_1 ci_high_0 ci_high_1 ci_low_0 ci_low_1
1:            5       90      100       100       110       80       90
2:           10       50       80        60        90       40       70
3:           15       40       70        50        80       30       60

关于r - 如何使用 tidyverse 中使用多个变量的传播函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65006939/

相关文章:

r - 线性模型的nest()后跟map()

r - 如何按日期获取滞后变量的差异?

r - 在 R6 类中包装 Shiny 的模块

r - 将两个 sampleID 的相应值连接到一个新的单列中

r - 根据组分配最大 n 值

r - 管道到 R 函数中的 return() 时的奇怪行为?

R dplyr : change the row value of columns having an specific name

r - 当名称存储在不同的向量中时如何为对象分配名称

r - 将分组数据过滤到分组发生变化的行

r - 使用 Purrr::map2 循环列名称的两个向量,以便有条件地将多个列重新编码为新变量