Reputation: 548
I have a dataframe like this:
Name<-c("v","v","x","y","z")
Position<-c(2,"5;7",3,198,"3;4")
Score<-c(0,100,200,144,3)
df<-data.frame(Name, Position, Score)
df
Name Position Score
1 v 2 0
2 v 5;7 100
3 x 3 200
4 y 198 144
5 z 3,4 3
In the column df$Position
, occasionally I have two (or more) numbers (for example in rows 2 and 5). I would like to duplicate these rows so each of them contains just one of these values. So the output looks like this:
Name Position Score
1 v 2 0
2 v 5 100
3 v 7 100
4 x 3 200
5 y 198 144
6 z 3 3
7 z 4 3
I would also want df$Position
to be numeric.
Upvotes: 1
Views: 254
Reputation: 887128
We can use separate_rows
from tidyr
library(tidyverse)
df %>%
separate_rows(Position, convert = TRUE)
# Name Position Score
#1 v 2 0
#2 v 5 100
#3 v 7 100
#4 x 3 200
#5 y 198 144
#6 z 3 3
#7 z 4 3
Upvotes: 1