0

I hope you are well.

I present myself. I am Yassine, PhD student in France and currently working in Food safety lab in France.

I need some help with a dataframe on R if possible.

Currently, I have the retention times (RT) in rows associated with each of the fragments (in column).

I would like to have all the fragments of the same row in a single column, with the same RT.

Here is what I have:

enter image description here

https://i.stack.imgur.com/RI67w.png 1

Here is what I would like to do in R:

enter image description here

[https://i.stack.imgur.com/FQ5Kf.png] 1

I thank you in advance for any advice or guidance ! I wish you all a very good day.

Respectfully, Yassine

LDT
  • 2,856
  • 2
  • 15
  • 32

3 Answers3

1

You can use unlist and subset the columns.

x <- data.frame(RT=1:3, F1=4:6, F2=7:9)

data.frame(x[1], F=unlist(x[-1]))
#    RT F
#F11  1 4
#F12  2 5
#F13  3 6
#F21  1 7
#F22  2 8
#F23  3 9

or if order matters.

data.frame(RT=rep(x[,1], each=ncol(x)-1), F=as.vector(t(x[-1])))
#  RT F
#1  1 4
#2  1 7
#3  2 5
#4  2 8
#5  3 6
#6  3 9
GKi
  • 37,245
  • 2
  • 26
  • 48
  • This was very helpfull thanks ! However, what is the purpose of each=ncol(x)-1 and F=as.vector(t(x[-1] ? Why the argument "-1" ?? – Yassine Sep 13 '21 at 16:28
  • Beside the Fragment columns, there is also the RT column, which needs to be excluded, what could be done with `-1`, when RT is in the first column. – GKi Sep 14 '21 at 06:51
1

Using stack. (Data borrowed from GKi)

cbind(x[1], F=unname(stack(x[-1])[-2]))
#   RT F
# 1  1 4
# 2  2 5
# 3  3 6
# 4  1 7
# 5  2 8
# 6  3 9
jay.sf
  • 60,139
  • 8
  • 53
  • 110
1

We can use dplyr::pivot_longer

library(dplyr)

df %>% pivot_longer(cols = matches("Fragment \\d+"),
                    names_to = "Fragment",
                    values_to = "value")
GuedesBF
  • 8,409
  • 5
  • 19
  • 37