Friday, 15 January 2010

r - Syntax (and/or functions) for applying an op over elements of one vector, using as arg elements of a 2nd vector -



r - Syntax (and/or functions) for applying an op over elements of one vector, using as arg elements of a 2nd vector -

i trying find right look creating vector result applying operation on vector, using, in vectorised way, elements of 2nd vector. utilize case have vector of raw values, , vector of breakpoints. want look give me result of applying sum of logical operation on breakpoints respect values in values vector. in other words:

given:

rawfoo <- c(30, 4, 22, 77, 1,169, 10) breaksfoo <- c(10,50, 80) resultfoo <- data.frame(breaks=breaksfoo, matching=numeric(length(breaksfoo)))

i want write single expression delivers column values resultfoo$matching, is: each value in breaksfoo, sum(rawfoo > breaksfoo[i]),

resultfoo breaks nmatching 1 10 3 2 50 2 3 80 1

i have been trying various forms of apply , having problems how express function. perhaps barking wrong tree? can supply multiple demonstration of failure if required. (but guess question simple doesn't need error messages disambiguate ;-)

you can in 3 steps:

write function that, given break, returns list of 2 element: break , result of sum(break > rawfoo).

than can utilize sapply apply function breaksfoo.

finally, need transform result of sapply, matrix, dataframe need.

the next code of these 3 steps in 1 statement:

as.data.frame(t(sapply(breaksfoo, function(x) list(breaks = x, nmatching = sum(x > rawfoo)))))

returns

breaks nmatching 1 10 2 2 50 5 3 80 6

r syntax apply

No comments:

Post a Comment