Vlad117 Vlad117 - 1 month ago 4x
R Question

Repeating function on each row of dataframe

I would like to apply a function so that for each loop the function would take new input parameters from rows of a data set and provide separate results for each loop.

Lets say I have a dataset like this:

df<-data.frame(A = 7:11, B = 1:5, C = 4:8, D = 10:14)

The function:

sm <- sum(a,b,c,d)

I would like to automize the following process so that the function will count sums for each row separately for the whole dataset:

loop (df[1,1],df[1,2],df[1,3],df[1,4])
loop (df[2,1],df[3,2],df[3,3],df[3,4])
loop (df[3,1],df[3,2],df[3,3],df[3,4])
loop (df[4,1],df[4,2],df[4,3],df[4,4])
loop (df[5,1],df[5,2],df[5,3],df[5,4])

I try to use
function, however, I cannot do that properly. Can somebody advise me a solution? Thank you.


Use rowSums

#[1] 22 26 30 34 38

If you still want to use your loop function, try this

#[1] 22 26 30 34 38