Hi:) what i'm trying to do is write a simple program to expand from shortest entry
for example
a-z
to longest write
for example
abcdefghijklmnouprstwxyz
Any ideas on how to implement that in R? Thanks
Hi:) what i'm trying to do is write a simple program to expand from shortest entry
for example
a-z
to longest write
for example
abcdefghijklmnouprstwxyz
Any ideas on how to implement that in R? Thanks
We could do
paste(letters[do.call(`:`, as.list(match( strsplit(str1, "-")[[1]],
letters)))], collapse="")
[1] "abcdefghijklmnopqrstuvwxyz"
The above could be wrapped in a function
f1 <- function(string1) {
paste(letters[do.call(`:`, as.list(match( strsplit(string1, "-")[[1]],
letters)))], collapse="")
}
Using the new data
i1 <- grep('-', df$letters)
df$letters[i1] <- sapply(df$letters[i1], f1)
df$letters
[1] "abc" "bcd" "cd" "abcd" "ab" "cd"
Or use regex
paste(grep(sprintf('[%s]', str1), letters, value = TRUE), collapse="")
Based on the new dataset
library(dplyr)
library(tidyr)
library(stringr)
df %>%
separate(letters, into = c('start', 'end'),
sep="(?<=[a-z])-?(?=[a-z])") %>%
transmute(new = map2_chr(match(start, letters),
match(end, letters), ~ str_c(letters[.x:.y], collapse="")))
-output
new
1 abc
2 bcd
3 cd
4 abcd
5 ab
6 cd
str1 <- "a-z"
df<-data.frame(letters=c("a-c","b-d","c-d","a-d", "ab", "cd"))