Search code examples
rdata.tablecalculationrecode

How to recode values in a matrix based on a calculation?


I have a question. I'm working on building a recommendation system in R, and I'm fairly new to the language. I can't seem to figure the following out.

I have a matrix like:

eventID g_26 g_27 g_28 g_29 g_30 g_31 g_32 g_33 g_34 g_35 g_36 g_37 g_38 g_39 g_40 g_41 g_42 g_43
1:    1010    0    0    1    0    0    0    0    0    0    0    0    0    1    0    1    0    0    0
2:    1016    1    0    1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1
3:    1019    0    0    0    0    0    0    0    0    0    0    0    1    0    0    0    0    0    0
4:    1053    1    0    1    0    0    0    0    0    0    0    0    0    0    1    1    0    0    0
5:    1168    0    0    0    0    0    0    0    0    1    0    1    0    0    1    0    0    0    0
6:    1188    0    0    1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0

What I´d like to do is replace all values that have 1 to 1/sqrt(total # of 1's in that particular row).

I'm using the Data Table package as well if that makes it easier.

Thanks in advance!


Solution

  • We can specify the columns of interest in .SDcols (-1 implies we selected all the columns except the first column), get the sum of each row in the Subset of Data.table with Reduce and +, take the square root (sqrt), divide by 1, multiply with the Subset of data.table (.SD) and assign (:=) it to the columns of interest

    dt[, (2:ncol(dt)) := .SD*1/sqrt(Reduce(`+`, .SD)), .SDcols = -1]