1

I'm currently working with RStudio and I'm having some problems. I've researched some functions (reshape,merge, combine, etc.) but couldn't get my problem solved.

I have this kind of data in excel:

    ID_No Measurament_1 Measurament_2 Measurament_3 Measurament_4
1 a                1            2            3            4
2 b                5            6            7            8
3 c                10           20           30           40
4 d                60           70           80           90 

and I want to transform it in this way:

ID_No        Measurament
 1 a              1
 2 a              2
 3 a              3
 4 a              4
 5 b              5
 6 b              6
 7 b              7
 8 b              8
 9 c              10
10 c              20
11 c              30
12 c              40
13 d              60
14 d              70
15 d              80
16 d              90

Can you guys help me out? There should be an easy command for this task but I don't get it.

Matt
  • 7,255
  • 2
  • 12
  • 34
basti41a
  • 153
  • 1
  • 6

2 Answers2

0

You can try with df your dataframe:

library(reshape2)
df2 <- melt(df,idvar='ID_No')
Duck
  • 39,058
  • 13
  • 42
  • 84
0

There's also the Tidyverse way of doing it, which gives you a lot of control over what columns you want to make long instead of wide:

library(dplyr)
library(tidyr)
measurements <- data.frame(ID_No=c("a", "b", "c", "d"), 
                           m_1=c(1,5,10,60),
                           m_2=c(2, 6, 20, 70),
                           m_3=c(3, 7, 30, 80),
                           m_4=c(4, 8, 40, 90),
                           stringsAsFactors = FALSE
)
measurements %>% pivot_longer(cols = starts_with("m_"),
                              values_to = "Measurement")

This additionally gives you the original field names (m_1, m_2, etc.) as another column, if you want to track that as well. If not, you can can just drop that column.