Vlad117 - 10 months ago 36

R Question

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:

`loop<-function(a,b,c,d){`

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

return(sm)

}

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

`apply`

Answer

Use `rowSums`

```
rowSums(df)
#[1] 22 26 30 34 38
```

If you still want to use your `loop`

function, try this

```
mapply(loop,df[,1],df[,2],df[,3],df[,4])
#[1] 22 26 30 34 38
```

Source (Stackoverflow)