Create a test basis:
b <- data_frame(x = 1:10,y = 1:10, string = rep("123-235-203", 10))
With the following code you can get what you wanted:
b %>%
separate(string, into = c('s1', 's2', 's3'), sep = '-') %>%
gather(string, valor, -x, -y) %>%
select(-string) %>%
arrange(x)
- The function
separate
of tidyr
turns your string into three columns (S1, s2 and S3).
- The function
gather
of tidyr
multiplies the lines.
- The function
select
of dplyr
remove the new column string
that is no longer needed.
- The
arrange
is just to make it easier to understand.
The results are below:
# Source: local data frame [30 x 3]
#
# x y valor
# 1 1 1 123
# 2 1 1 235
# 3 1 1 203
# 4 2 2 123
# 5 2 2 235
# 6 2 2 203
# 7 3 3 123
# 8 3 3 235
# 9 3 3 203
# 10 4 4 123
# .. . . ...
In the case that strings can have variable sizes, but there is a maximum of "-"’s you can do so:
b <- data_frame(x = 1:10,y = 1:10, string = rep(c("123-203", "123-203-555"), length.out = 10))
b %>%
separate(string, sep = '-', into = c("s1", "s2", "s3"), extra = "merge") %>%
gather(string, valor, -x, -y, na.rm = T) %>%
select(-string) %>%
arrange(x)
- added the argument
extra = "merge"
in the separate
so that he does not return error.
- added the argument
na.rm = T
so that it does not create lines with NA
.
You want the string column to turn three columns?
– Carlos Cinelli
@Carloscinelli Sorry, there it is. I want to separate the string, separate by the strokes and turn into 3 lines.
– Guilherme Duarte