I am dealing with strings having two separators "*" and "|", and they are used in strings such as:
"3\*4|2\*7.4|8\*3.2"
Where the number right before "*" denotes frequency and the float or integer right after "*" denotes value. These value frequency pairs are separated using "|".
So from "3\*4|2\*7.4|8\*3.2"
, I would like to get a following vector:
"4","4","4","7.4","7.4","3.2","3.2","3.2","3.2","3.2","3.2","3.2","3.2"
I have come up with following syntax, which completes with no errors and warnings, but the end results something else than expected:
strsplit("3*4|2*7.4|8*3.2", "[*|]") %>% #Split into a vector with two different separator characters
unlist %>% #strsplit returns a list, so let's unlist it
mapply(FUN = rep,
x = .[seq(from = 2, to = length(.), by = 2)], #these sequences mean even and odd index in this respect
times = .[seq(from = 1, to = length(.), by = 2)], #rep() flexibly accepts times argument also as string
USE.NAMES = FALSE) %>%
unlist #mapply returns a list, so let's unlist it
[1] "4" "4" "4" "7.4" "7.4" "7.4" "7.4" "3.2" "3.2" "4" "4" "4" "4" "4" "4" "4" "7.4" "7.4" "7.4" "7.4" "7.4" "7.4" "7.4" "7.4" "3.2" "3.2" "3.2"
As you can see, something weird has happened. "4" has been repeated three times, which is correct, but "7.4" has been repeated four times (incorrectly) and so on.
What is going on here?