简体   繁体   English

为另一列中的每个唯一值向数据框添加新列

[英]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.

相关问题 如何为数据框 A 中存在的列的每个唯一值在数据框 B 中创建一个新列? - How can I create a new column in a data frame B for each unique value of a column present in data frame A? 如何使用每列的筛选数据在另一个数据框中创建具有自定义列的新数据框 - How to create new data frame with custom columns out of another data frame, on filtered data per each column 通过根据另一个数据框中列的值从一个数据框中提取列来创建新数据框 - creating a new data frame by extracting columns from one data frame based on the value of column in another data frame 在另一个数据框的列上匹配一个数据框的列,如果匹配则添加一个新列 - Matching a column from a data frame on the columns of another data frame and if they match add a new column 在数据框中添加列标题是另一列的唯一值的列 - Add columns in a data frame whose column headers are unique values of another column 将每一列添加到新的数据框中 - Add each column to a new data frame R:根据另一列中的值在数据框的新列中添加值 - R: Add value in new column of data frame depending on value in another column 合并数据框中的两列,并通过引用另一列来选择每行要取的值 - Combine two columns in a data frame and select which value to take for each row by referencing another column 将向量转换为data.frame,每个唯一值一列 - Convert a vector to data.frame, one column for each unique value 垂直合并来自不同数据帧的列,并添加新列,该列的值对应于源自 - Vertically merge columns from different data frames and add new column with value corresponding to data frame originated from
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM