markleeds at verizon.net
2006-Jun-26 17:40 UTC
[R] probably need to se sapply but i can't get it
Hi : I think I need to use sapply but I can't figure this out. Suppose I have two vectors : tempa ( 4, 6,10 ) and tempb ( 11,23 ,39 ) I want a function that returns 4:11,6:23 and 10:39 as vectors. I tried : sapply(1:length(tempa) function (z) seq(tempa[z],tempb[z]) but i got 3 really strange vectors back in the sense that the numbers in them did not make no sense to me. obviously, i must be doing something wrong. thanks a lot. mark
Marc Schwartz (via MN)
2006-Jun-26 17:54 UTC
[R] probably need to se sapply but i can't get it
On Mon, 2006-06-26 at 12:40 -0500, markleeds at verizon.net wrote:> Hi : I think I need to use sapply but I can't figure this out. > > Suppose I have two vectors : tempa ( 4, 6,10 ) and tempb > ( 11,23 ,39 ) > > > I want a function that returns 4:11,6:23 and 10:39 as vectors. > > I tried : > > sapply(1:length(tempa) function (z) seq(tempa[z],tempb[z]) > > but i got 3 really strange vectors back in the sense that the numbers > in them did not make no sense to me. obviously, > i must be doing something wrong. thanks a lot. > > markMark, Try this using mapply(): tempa <- c(4, 6, 10) tempb <- c(11, 23, 39)> mapply(seq, from = tempa, to = tempb)[[1]] [1] 4 5 6 7 8 9 10 11 [[2]] [1] 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 [[3]] [1] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 [23] 32 33 34 35 36 37 38 39 You will get a list back in this case and you can then deal with the 3 vectors as you require. Each vector is a different length, so a list is about the only way to return them here. See ?mapply for more info. HTH, Marc Schwartz
On Mon, 26 Jun 2006, markleeds at verizon.net wrote:> Hi : I think I need to use sapply but I can't figure this out. > > Suppose I have two vectors : tempa ( 4, 6,10 ) and tempb > ( 11,23 ,39 ) > > > I want a function that returns 4:11,6:23 and 10:39 as vectors. > > I tried : > > sapply(1:length(tempa) function (z) seq(tempa[z],tempb[z]) > > but i got 3 really strange vectors back in the sense that the numbers in them did not make no sense to me. obviously, > i must be doing something wrong. thanks a lot.An easier way to do this is mapply(seq,tempa,tempb) Your approach should have worked. It's hard to tell why it didn't because there are two syntax errors in your example so it clearly isn't actually what you did. Fixing them, I get> sapply(1:length(tempa), function (z) seq(tempa[z],tempb[z]))[[1]] [1] 4 5 6 7 8 9 10 11 [[2]] [1] 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 [[3]] [1] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 [26] 35 36 37 38 39 as you wanted. -thomas