[英]Add new columns to data frame for each unique value in another column
I'd like to add a new column for each unique value in another column.我想为另一列中的每个唯一值添加一个新列。 Then for each of these columns the value will either be the value from the other column, or zero.
然后,对于这些列中的每一列,值要么是另一列的值,要么为零。
For the example below i would like to add 4 new columns (A:D), for column B would be (0,0,0,0,5,6,7,8,0,0,0,0,0,0,0,0)
etc.对于下面的示例,我想添加 4 个新列 (A:D),因为 B 列将是
(0,0,0,0,5,6,7,8,0,0,0,0,0,0,0,0)
等
df <- data.frame(Group=rep(c('A', 'B', 'C', 'D'), each=4),
score=1:16)
df
Using map_dfc
:使用
map_dfc
:
library(purrr)
library(dplyr)
map_dfc(setNames(unique(df$Group), unique(df$Group)),
~ ifelse(df$Group == .x, df$score, 0)) %>%
bind_cols(df, .)
Group score A B C D
1 A 1 1 0 0 0
2 A 2 2 0 0 0
3 A 3 3 0 0 0
4 A 4 4 0 0 0
5 B 5 0 5 0 0
6 B 6 0 6 0 0
7 B 7 0 7 0 0
8 B 8 0 8 0 0
9 C 9 0 0 9 0
10 C 10 0 0 10 0
11 C 11 0 0 11 0
12 C 12 0 0 12 0
13 D 13 0 0 0 13
14 D 14 0 0 0 14
15 D 15 0 0 0 15
16 D 16 0 0 0 16
Or in base R:或者在基数 R 中:
cbind(df,
sapply(unique(df$Group), \(x) ifelse(df$Group == x, df$score, 0)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.