Reputation: 479
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?
Upvotes: 1
Views: 81
Reputation: 115
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)
Upvotes: 2
Reputation: 887108
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
Upvotes: 2