In R, I have a vector, say vec = c(1,2,...10).
What I want to do is loop through the vector, and for each element apply a function that again involves looping through the vector. I can do it with for loops, but I want to do it with built in functions.
For a concrete example, I'd like to take each element of the vector, and take the sum of the numbers that are greater than the current element I'm looking at. Then I'd get a new vector of the same length.
vec=c(1,2,3,4,5,6,7,8,9,10)
newvec=c()
for (i in 1:10){
x=vec[i]
sum=0
for (j in 1:10){
if (vec[j]>x){
sum=sum+vec[j]
}}
newvec=c(newvec,sum)}
newvec
What's the best way to accomplish this with built in functions, hopefully that applies even more generally than this example (e.g. multiple conditions being compared, not just vec[j]>x)? Any help is appreicated!
With sapply
. For each element of vec
(say x
), it returns the sum
of values of vec
that are greater than x
.
sapply(vec, \(x) sum(vec[vec > x]))
# [1] 54 52 49 45 40 34 27 19 10 0