I'm changing morse code into english sentence using functions but it doesn't work well.
This is the basic data frame for morse code and english
a <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z", "", " ")
b <- c("dD", "Dddd", "DdDd", "Ddd", "d", "ddDd", "DDd", "dddd", "dd", "dDDD",
"DdD", "dDdd", "DD", "Dd", "DDD", "dDDd", "DDdD", "dDd", "ddd", "D",
"ddD", "dddD", "dDD", "DddD", "DdDD", "DDdd", "s", "ss")
moth <- data.frame(a,b)
names(moth)=c("Alphabet", "moth_code")
And this is the sentence I want to interpret.
d<- ("DdDDsDDDsddDssdDDsddsdDddsdDddssddDdsdDsDdDdsdssDDsdDsDdsDdDDssDddsdsddDdsdsdDsDsdddssddsDdssdDddsddsddDdsdssDdddsddDsDssDdsdsdddDsdsdDdssdDddsdsDssDdDDsDDDsddDsdDdsdddsdsdDddsddDdssDdddsdssDddsdsddDdsdsdDsDsdsDdd")
f <- c()
g <- c()
This is the function I made.
moth_Alphabet <- function(x){
x <- strsplit(x, split='s')
x <- unlist(x)
for(i in 1:69){
f[i]<-match(d[i], moth$moth_code)
g[i]<-moth$Alphabet[f[i]]
if(is.na(g[i])==TRUE){
g[i]<-" "
}
}
h <- paste(g, collapse="")
l <- sub('y', 'Y', h)
l
}
moth_Alphabet(d)
moth_Alphabet(d) should be "You will face many defeats in life but never let yourself be defeated"
but it didn't work.
This is what I tried.
d <- strsplit(d, split='s')
d <- unlist(d)
d
moth_Alphabet <- function(x){
x <- strsplit(x, split='s')
x <- unlist(x)
for(i in 1:69){
f[i]<-match(d[i], moth$moth_code)
g[i]<-moth$Alphabet[f[i]]
if(is.na(g[i])==TRUE){
g[i]<-" "
}
}
h <- paste(g, collapse="")
l <- sub('y', 'Y', h)
l
}
moth_Alphabet(d)
d <- strsplit(d, split='s')
d <- unlist(d)
d
after coding this before the 'moth_Alphabet' function, the code worked well but 'moth_Alphabet' code itself without the upper code doesn't work well. I need your help. thanks :)
CodePudding user response:
The d[i]
inside the function doesn't work as d
is a single string.
moth_Alphabet <- function(x){
f <- c()
g <- c()
x <- strsplit(x, split='s')
x <- unlist(x)
for(i in seq_along(x)){
tmp <-match(x[i], moth$moth_code)
f <- c(f, tmp)
tmp2 <- moth$Alphabet[tmp]
if(is.na(tmp2)){
tmp2<-" "
}
g <- c(g, tmp2)
}
h <- paste(g, collapse="")
l <- sub('y', 'Y', h)
l
}
-testing
> d<- "DdDDsDDDsddDssdDDsddsdDddsdDddssddDdsdDsDdDdsdssDDsdDsDdsDdDDssDddsdsddDdsdsdDsDsdddssddsDdssdDddsddsddDdsdssDdddsddDsDssDdsdsdddDsdsdDdssdDddsdsDssDdDDsDDDsddDsdDdsdddsdsdDddsddDdssDdddsdssDddsdsddDdsdsdDsDsdsDdd"
> moth_Alphabet(d)
[1] "You will face many defeats in life but never let yourself be defeated"