R中按行总计的一般一列

General a column from row-wise totals in R

我有一个 table 看起来像这样:

df <- tribble(
  ~name, ~point, ~time,
  "A", 1, 1,
  "B", 1, 1,
  "W", 2, 1,
  "A", 3, 2,
  "B", 1, 2,
  "W", 4, 2,
)

# A tibble: 6 x 3
  name  point  time
  <chr> <dbl> <dbl>
1 A         1     1
2 B         1     1
3 W         2     1
4 A         3     2
5 B         1     2
6 W         4     2

并且我想将 point 列的值转换为新列中每个条目的值,特别是名称等于 W 的位置,如下所示:

# A tibble: 6 x 4
  name  point  time W_point_value
  <chr> <dbl> <dbl>         <dbl>
1 A         1     1             2
2 B         1     1             2
3 W         2     1             2
4 A         3     2             4
5 B         1     2             4
6 W         4     2             4

我知道我可以使用过滤器来获取结果,但由于大小调整不当,我很难将其附加到新列中。

谢谢

你可以这样做:

df %>% 
  group_by(time) %>% 
  mutate(W_point_time = point[name == "W"])

# A tibble: 6 x 4
# Groups:   time [2]
  name  point  time W_point_time
  <chr> <dbl> <dbl>        <dbl>
1 A         1     1            2
2 B         1     1            2
3 W         2     1            2
4 A         3     2            4
5 B         1     2            4
6 W         4     2            4