I am trying to create a function, let's say "generic" to add rows in a database.
My idea is that the function "recognizes" the numeric elements in the database and adds by rows.
Suppose I have the data of the following image:
The function would take from the second column and add 2+3+3+6+4+2+0 and so on.
The code I have written so far is as follows:
suma_renglones < - function (x) {
y = integer(nrow(x))
for (i in 1: nrow(x)) {
for (j in 1: ncol(x)) {
if (is.numeric(x[i, j])) {
y[i] = y[i] + (x[i, j])
}
}
y[i]
}
}
However, when applying the function, the column designated to store the result of the sum shows only NULL results. Any help or guidance will be greatly appreciated.
PS: I know there are already solutions about it elsewhere as shown in this example , however my intention is to make a "own" function.
Let's see, you say that you are adding in a column of the original matrix, but you are not doing that, you are simply creating a vector with the sums
y
, also remember that your routine cannot modify an object passed by parameter because it is outside its "scope ", what can be done, is to return a new matrix with the additional column and lastly "step" on the original objectReformulating your code a bit
Return
What are we doing?
y
that contains the sum of each rowx
a new column "sum" with the sumsx
since the function cannot modify the original array, being out of its "scope"Here I have a solution using
dplyr
andtidyr
without loops, so it should be faster:I build an example with the first 2 lines
First I have to "transpose" the dataframe, which I do with
gather
andspread
to calculate the sum of each column, and then I have to transpose the result again and do ainner_join
with the original table. At last, what I do is change the name of the columns andselect
order the result so that the sum remains as the last column.Dear Patrick,
The solution I designed was this:
Comparing it to your code, I think I didn't do too badly in the end, right? However, your solution is clearly much cleaner and more efficient. I really appreciate the time you took to help me. Greetings again :)