Reputation: 119
So I have this dataframe:
mass value
1 2390.421 0.0001376894
2 2390.713 0.0001362054
3 2391.004 0.0001346138
4 2391.296 0.0001329289
5 2391.588 0.0001311646
6 2391.879 0.0001293351
What I need is that the mass values becomes the column names:
2390.421 2390.713 2391.004 .....
0.0001376894 0.0001362054 0.0001346138 .....
I tried reshape, unstack, do.call, but I still couldn't do it.
What can I do?
Upvotes: 0
Views: 731
Reputation: 102880
A base R option
> t(unstack(rev(df)))
2390.421 2390.713 2391.004 2391.296 2391.588
res 0.0001376894 0.0001362054 0.0001346138 0.0001329289 0.0001311646
2391.879
res 0.0001293351
or a data.table
option
> dcast(setDT(df), . ~ mass, value = "value")[, -1]
2390.421 2390.713 2391.004 2391.296 2391.588
1: 0.0001376894 0.0001362054 0.0001346138 0.0001329289 0.0001311646
2391.879
1: 0.0001293351
Data
> dput(df)
structure(list(mass = c(2390.421, 2390.713, 2391.004, 2391.296,
2391.588, 2391.879), value = c(0.0001376894, 0.0001362054, 0.0001346138,
0.0001329289, 0.0001311646, 0.0001293351)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
Upvotes: 1
Reputation: 887951
We can use transpose
from data.table
data.table::transpose(df1, make.names = 'mass')
# 2390.421 2390.713 2391.004 2391.296 2391.588 2391.879
#1 0.0001376894 0.0001362054 0.0001346138 0.0001329289 0.0001311646 0.0001293351
Or with deframe/as_tibble_row
library(tibble)
library(dplyr)
deframe(df1) %>%
as_tibble_row
# A tibble: 1 x 6
# `2390.421` `2390.713` `2391.004` `2391.296` `2391.588` `2391.879`
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 0.000138 0.000136 0.000135 0.000133 0.000131 0.000129
Or using xtabs
from base R
xtabs(value ~ mass, df1)
#mass
# 2390.421 2390.713 2391.004 2391.296 2391.588 2391.879
#0.0001376894 0.0001362054 0.0001346138 0.0001329289 0.0001311646 0.0001293351
It is a matrix
, but can be converted to data.frame
as.data.frame.list(xtabs(value ~ mass, df1) , check.names = FALSE)
# 2390.421 2390.713 2391.004 2391.296 2391.588 2391.879
#1 0.0001376894 0.0001362054 0.0001346138 0.0001329289 0.0001311646 0.0001293351
df1 <- structure(list(mass = c(2390.421, 2390.713, 2391.004, 2391.296,
2391.588, 2391.879), value = c(0.0001376894, 0.0001362054, 0.0001346138,
0.0001329289, 0.0001311646, 0.0001293351)), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5", "6"))
Upvotes: 2
Reputation: 1587
What about a dplyr
solution:
library(tidyverse)
df1 %>% pivot_wider(names_from = a, values_from = b)
# A tibble: 1 x 6
`2390.421` `2390.713` `2391.004` `2391.296` `2391.588` `2391.879`
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.000138 0.000136 0.000135 0.000133 0.000131 0.000129
Upvotes: 4