1

My DF looks like this:

ID  V1    V2  V3
A   100  200    
B   100     
C   300     
D   400     
E   223  233   4

I want to transform it in R, such that the multiple 'V' columns come under one another with repeating IDs:

ID  V1
A   100
A   200
B   100
C   300
D   400
E   223
E   233
E   4

What is the best way of doing this in R or Excel?

Krupa Kapadia
  • 469
  • 4
  • 11
  • 1
    Possible duplicate of [Reshaping time series data from wide to tall format (for plotting)](http://stackoverflow.com/questions/1181060/reshaping-time-series-data-from-wide-to-tall-format-for-plotting) – zx8754 Apr 18 '16 at 10:20

2 Answers2

2

We can use melt

library(data.table)
setnames(melt(setDT(df), id.var="ID", na.rm=TRUE)[order(ID), -2, with = FALSE], 2, "V1")[]
#   ID  V1
#1:  A 100
#2:  A 200
#3:  B 100
#4:  C 300
#5:  D 400
#6:  E 223
#7:  E 233
#8:  E   4
akrun
  • 874,273
  • 37
  • 540
  • 662
2

You can also try tidyr:

library(tidyr)
df <- df %>% gather(new, V1, 2:4) %>% filter(!is.na(V1)) 

If you don't want the "new" column add this cody (library "dplyr"):

%>% select(id, V1)