【发布时间】:2020-08-01 11:05:24
【问题描述】:
我有一个如下所示的数据框:
ID Code Desc
1 0A Red
1 NA Red
2 1A Blue
3 2B Green
我想首先创建一个新列,在其中连接 ID 相同的代码列中的值。所以:
ID Combined_Code Desc
1 0A | NA Red
2 1A Blue
3 2B Green
那我想把原来的 Code 栏目拿出来传一下。在这种情况下,值将是每个代码针对给定 ID 显示的次数。所以:
ID Combined_Code 0A NA 1A 2B Desc
1 0A | NA 1 1 0 0 Red
2 1A 0 0 1 0 Blue
3 2B 0 0 0 1 Green
我试过了:
sample_data %>%
group_by(ID) %>%
summarise(Combined_Code = paste(unique(Combined_Code), collapse ='|'))
这适用于创建串联。但是,我不能让它与传播一起工作:
sample_data %>%
group_by(ID) %>%
summarise(Combined_Code = paste(unique(Combined_Code), collapse ='|'))
sample_data <- spread(count(sample_data, ID, Combined_Code, Desc., Code), Code, n, fill = 0)
这样做会扩展,但会丢弃串联。我也尝试过使用过滤器而不是摘要,这给出了相同的结果。这导致:
ID Combined_Code 0A NA 1A 2B Desc
1 0A 1 0 0 0 Red
1 NA 0 1 0 0 Red
2 1A 0 0 1 0 Blue
3 2B 0 0 0 1 Green
最后,我尝试了通过汇总函数进行管道传播:
sample_data %>%
group_by(ID) %>%
summarise(Combined_Code = paste(unique(Combined_Code), collapse ='|')) %>%
spread(count(sample_data, ID, Combined_Code, Desc., Code), Code, n, fill = 0)
这会导致错误:
Error: `var` must evaluate to a single number or a column name, not a list
Run `rlang::last_error()` to see where the error occurred.
我能做些什么来解决这些问题?
【问题讨论】: