Nico - 1 year ago 57
R Question

Replacing vector elements warning message

I have a function that encrypts strings:

``````encrypt <- function(text, movement)
{

vec <- c(LETTERS, letters," ",".",",","!","?")
vec2 <- c(LETTERS, letters," ",".",",","!","?")
l <- length(vec)
n <- -movement%%l
if(n==0)
text2 <- text

if (n!=0)
{
tmp <- vec2[(l-n+1):l]
vec2[(n+1):l] <- vec2[1:(l-n)]
vec2[1:n] <- tmp
vec2
i <- 1
text2 <- text
text2 <- strsplit(text2 ,split='', fixed=TRUE)
text2 <- as.vector(unlist(text2))
lang <- length(text2)

while(i<=lang)
{
if(text2[i] %in% vec)
{
repl <- grep(text2[i], vec)
text2[i] <- vec2[repl]
i <- i+1
}
else {
i <- i+1
}
}
}
text2 <- as.list(text2)
text2 <- paste(text2, collapse='')
return(text2)
}
``````

Now let's say I want to encrypt the message

``````"Hello!",
``````

with the movement beeing 4. The function returns

``````"LippsC",
``````

which is correct. Now I want to encrypt the message

``````"Hello?"
``````

which should return

``````"LippsD"
``````

However the real return is

``````"LippsE"
``````

with the following warning message:

``````Warning message:
In text2[i] <- vec2[repl] :
number of items to replace is not a multiple of replacement length
``````

I have the same problem when I want to encrypt

``````"Hello.",
``````

which once again returns

``````"LippsE",
``````

followed by the same warning message.

I don't have the problem when my string contains a blank space, a comma or exclamation point. It seems like a "." or "?" gets interpreted as an "A".

If anybody knows why that is and how it could be fixed, I would be really greatful!

Nico

You need to define `fixed = TRUE` in your `grep()` call, so that `grep` ignores the special function of certain reg-exp characters like `?` or `.`.

``````encrypt <- function(text, movement)
{

vec <- c(LETTERS, letters," ",".",",","!","?")
vec2 <- c(LETTERS, letters," ",".",",","!","?")
l <- length(vec)
n <- -movement%%l
if(n==0)
text2 <- text

if (n!=0)
{
tmp <- vec2[(l-n+1):l]
vec2[(n+1):l] <- vec2[1:(l-n)]
vec2[1:n] <- tmp
vec2
i <- 1
text2 <- text
text2 <- strsplit(text2 ,split='', fixed=TRUE)
text2 <- as.vector(unlist(text2))
lang <- length(text2)

while(i<=lang)
{
repl <- grep(text2[i], vec, fixed = TRUE)
text2[i] <- vec2[repl]
i <- i+1
}
}
text2 <- as.list(text2)
text2 <- paste(text2, collapse='')
return(text2)
}

> encrypt("Hello?", 4)
[1] "LippsD"
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download