apply - MAPPLY across a vector in R -
i've seen several examples on google, still don't understand quite how works
here's i'm trying do.
i have text array
> v <- c("aa","bb","cc","dd","ee","ff") > v [1] "aa" "bb" "cc" "dd" "ee" "ff"
i output array of length length(v)-2 (=4) composed of
[1] "aabbcc" "bbccdd" "ccddee" "ddeeff"
which vector concatenations of 3 successive elements of v
i'm thinking of using mapply
mapply(function(x,i){paste(x[i:i+2],sep="",collapse="")},v,1:(length(v)-2))
but thats not right syntax
thanks
here's solution in case project needs many successive elements. there other approaches, mapply
one:
mapply(function(x,y) paste(v[x:y], collapse=""), 1:(length(v)-2), 3:length(v)) #[1] "aabbcc" "bbccdd" "ccddee" "ddeeff"
as per comments, can create function , use lapply
list:
paste2 <- function(vec, n=3) { mapply(function(x,y) paste(vec[x:y], collapse=""), 1:(length(vec)-(n-1)), n:length(vec)) } ## single vector still works paste2(v) #[1] "aabbcc" "bbccdd" "ccddee" "ddeeff" ## list lst <- rep(list(v), 2) lapply(lst, paste2) #[[1]] #[1] "aabbcc" "bbccdd" "ccddee" "ddeeff" # #[[2]] #[1] "aabbcc" "bbccdd" "ccddee" "ddeeff"
Comments
Post a Comment