Question

I'm a newbie to R, but I'm trying to make a sliding window in R.

Using loops I can it like this, but this gets very inefficient.

results=c(1:7)
letters=c("A","B","C","D","E","F","G","H","I","J")
for(i in 1:7){
results[i]=paste(letters[i:(i+3)],collapse="")
}

How can I use an apply function to get the same output?

Was it helpful?

Solution 2

Here is one way to do this

sapply(1:7, function(i) {
  paste(letters[i:(i+3)], collapse = '')
})

OTHER TIPS

A little different to Ramnath's answer:

lets <- LETTERS[1:10]
substring(paste(lets,collapse=""),1:7,4:10)
#[1] "ABCD" "BCDE" "CDEF" "DEFG" "EFGH" "FGHI" "GHIJ"

With the zoo time series package:

apply(rollapply(letters,4,c), 1, paste, collapse="")
[1] "ABCD" "BCDE" "CDEF" "DEFG" "EFGH" "FGHI" "GHIJ"

A "roll your own" way just for fun:

## n letters
nl <- 10
## length of string
len <- 4
## note I use the inbuilt LETTERS
apply(matrix(LETTERS[seq_len(nl)], nl + 1, len), 1, paste, collapse = "")[seq_len(nl - len + 1)]

(Leaves you with a warning based on incomplete recycling, but I like the trick of using a matrix to provide the offset for rolling windows).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top