根据类别向 R 数据帧添加包含行值的列

问题描述 投票:0回答:1

所以我有一个以下结构的数据框,我们称其为 df0:

类别 a b c d
1989 1 0.3 0.7 0.43 321
1989 1 0.3 0.7 0.43 321
1989 2 0.2 0.4 0.5 174
1989 2 0.2 0.4 0.5 174
1989 2 0.2 0.4 0.5 174
1989 3 0.6 0.2 3.0 224
1990 1 0.6 0.2 3.0 93
1990 1 0.6 0.2 3.0 93
1990 2 0.3 0.7 4.0 293
1990 3 0.9 0.6 2.0 13

我需要将其变成以下内容。基本上,我想为每年添加一列,其中包含每个类别的 c 值。像这样:

类别 a b c d c1 c2 c3
1989 1 0.3 0.7 0.43 321 0.43 0.5 3.0
1989 1 0.3 0.7 0.43 321 0.43 0.5 3.0
1989 2 0.2 0.4 0.5 174 0.43 0.5 3.0
1989 2 0.2 0.4 0.5 174 0.43 0.5 3.0
1989 2 0.2 0.4 0.5 174 0.43 0.5 3.0
1989 3 0.6 0.2 3.0 224 0.43 0.5 3.0
1990 1 0.6 0.2 3.0 93 3.0 4.0 2.0
1990 1 0.6 0.2 3.0 93 3.0 4.0 2.0
1990 2 0.3 0.7 4.0 293 3.0 4.0 2.0
1990 3 0.9 0.6 2.0 13 3.0 4.0 2.0

我不知道如何计算这个。我的第一个想法是为每年创建子数据帧,然后从中创建每个 c 值的向量,但这看起来非常乏味,我无法让它工作。

有人对此有意见或解决方案吗?

KR

r dataframe data-manipulation transpose
1个回答
0
投票

一种方法:

library(dplyr)
library(tidyr)

df %>%
  reframe(unique_c = unique(c), .by = year) %>%
  mutate(row = row_number(), .by = year) %>%
  pivot_wider(names_from = row, names_prefix = "c", values_from = unique_c) %>%
  left_join(df, by = join_by(year)) %>%
  relocate(year, category, a:d)

#   year category     a     b     c     d    c1    c2    c3
#   <int>    <int> <dbl> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
# 1  1989        1   0.3   0.7  0.43   321  0.43   0.5     3
# 2  1989        1   0.3   0.7  0.43   321  0.43   0.5     3
# 3  1989        2   0.2   0.4  0.5    174  0.43   0.5     3
# 4  1989        2   0.2   0.4  0.5    174  0.43   0.5     3
# 5  1989        2   0.2   0.4  0.5    174  0.43   0.5     3
# 6  1989        3   0.6   0.2  3      224  0.43   0.5     3
# 7  1990        1   0.6   0.2  3       93  3      4       2
# 8  1990        1   0.6   0.2  3       93  3      4       2
# 9  1990        2   0.3   0.7  4      293  3      4       2
#10  1990        3   0.9   0.6  2       13  3      4       2
© www.soinside.com 2019 - 2024. All rights reserved.