I have a tibble called df in the form:
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
It can be generated by:
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)))
I would like to rearrange it to have
sample Pb208 Pb207 Pb206
SRM1 301 250 200
SRM1 305 254 202
SAM1 311 262 157
SAM1 325 261 204
I tried with the tidyr package using:
df %>%
select(sample, nuclide, intensity) %>%
group_by(sample) %>%
mutate(row = 1:n()) %>%
spread(nuclide, intensity) %>% select(-row)
but it produced a different result with lots of undesired NAs.
It is very important that during the transformation the names of the samples in the dataset should retain their original order and that no aggregation function is used. Especially the first condition it is what makes different my problem from other similar previously posted.
The solution would then be applied to a much larger dataset with more than 20000 rows.