【发布时间】:2017-02-22 11:48:56
【问题描述】:
我有一个名为 df 的小标题,格式为:
sample nuclide intensity
SRM1 Pb206 200
SRM1 Pb207 250
SRM1 Pb208 301
SRM1 Pb206 202
SRM1 Pb207 254
SRM1 Pb208 305
SAM1 Pb206 154
SAM1 Pb207 262
SAM1 Pb208 311
SAM1 Pb206 157
SAM1 Pb207 261
SAM1 Pb208 325
可以通过以下方式生成:
df <- tbl_df(
data.frame(sample = rep(c("SRM1", "SAM1"), each = 6),
nuclide = rep(c("Pb206", "Pb207", "Pb208"), 4),
intensity = c(200, 250, 301, 202, 254, 305, 154, 262, 311, 157, 261, 325)))
我想重新安排一下
sample Pb208 Pb207 Pb206
SRM1 301 250 200
SRM1 305 254 202
SAM1 311 262 157
SAM1 325 261 204
我尝试使用 tidyr 包:
df %>%
select(sample, nuclide, intensity) %>%
group_by(sample) %>%
mutate(row = 1:n()) %>%
spread(nuclide, intensity) %>% select(-row)
但它产生了一个不同的结果,有很多不受欢迎的 NA。
在转换过程中,数据集中样本的名称应保持其原始顺序并且不使用聚合函数,这一点非常重要。尤其是第一个条件,它使我的问题与以前发布的其他类似问题不同。
然后,该解决方案将应用于包含超过 20000 行的更大数据集。
【问题讨论】:
-
library(data.table); dcast(setDT(df)[, id := 1:.N, by = .(sample, nuclide)], id + sample ~ nuclide, value.var = 'intensity') -
不幸的是,此解决方案不保留 df 中定义的样本的原始顺序。
-
事后重新排序
-
@Jaap 在审核队列中发现了这个。我认为这不是完全重复,因为这里的区别在于键和值列的组合可能是重复的,应该强制出现在后续行中。
-
@Jaap 也 OP 标记了 dplyr -- 我喜欢 data.table 但对于初学者来说,dplyr 解决方案可能更有帮助