1

Let's suppose a data frame like this:

> df_in
GENE     ID     trans     score
ENS777   1122O   tra1      1.2
ENS777   1122O   tr2       0
ENS777   1122O   tr3       0
ENS777   1122O   tra2      1.6
ENS777   1122O   tr15      3.3
ENS777   1122O   tr1b      0
ENS999   1122O   tra1      0
ENS999   1122O   tr2       0
ENS999   1122O   tr3       0
ENS999   1122O   tra2      1.1
ENS999   1122O   tr15      2.3
ENS999   1122O   tr1b      0

I want to transpose the df_in from the third column where each row of trans would become a column along with it's corresponding value from score .

The output would look like this:

> df_out
GENE     ID     tra1   tr2   tr3  tra2   tr15   tr1b  
ENS777   1122O   1.2    0     0   1.6    3.3    0
ENS999   11220   0      0     0   1.1    2.3    0

I appreciate any help.

Maya_Cent
  • 471
  • 4
  • 10

1 Answers1

1

We could use pivot_wider

library(tidyr)
pivot_wider(df_in, names_from = trans, values_from = score)
# A tibble: 2 x 8
  GENE   ID     tra1   tr2   tr3  tra2  tr15  tr1b
  <chr>  <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 ENS777 1122O   1.2     0     0   1.6   3.3     0
2 ENS999 1122O   0       0     0   1.1   2.3     0

data

df_in <- structure(list(GENE = c("ENS777", "ENS777", "ENS777", "ENS777", 
"ENS777", "ENS777", "ENS999", "ENS999", "ENS999", "ENS999", "ENS999", 
"ENS999"), ID = c("1122O", "1122O", "1122O", "1122O", "1122O", 
"1122O", "1122O", "1122O", "1122O", "1122O", "1122O", "1122O"
), trans = c("tra1", "tr2", "tr3", "tra2", "tr15", "tr1b", "tra1", 
"tr2", "tr3", "tra2", "tr15", "tr1b"), score = c(1.2, 0, 0, 1.6, 
3.3, 0, 0, 0, 0, 1.1, 2.3, 0)), class = "data.frame", row.names = c(NA, 
-12L))
akrun
  • 874,273
  • 37
  • 540
  • 662