I have this code to do a series of multiplication and addition in R. Could someone give me a suggestion to use *apply to make it neater and shorter?
I looked around with keywords such as “series”, “multiplication” but did not get anywhere. If this question has been posted before, please let me know the link. Thank you.
df1n is a data.frame with >78 variables and 215 observation.
dff[,3]<-(df1n[5]*((df1n[25]*df1n[26]*df1n[27]) + (df1n[28]*df1n[29]*df1n[30]) +
(df1n[31]*df1n[32]*df1n[33]) + (df1n[34]*df1n[35]*df1n[36]) +
(df1n[37]*df1n[38]*df1n[39]) + (df1n[40]*df1n[41]*df1n[42]) +
(df1n[61]*df1n[62]*df1n[63]) + (df1n[64]*df1n[65]*df1n[66]) +
(df1n[67]*df1n[68]*df1n[69]) + (df1n[70]*df1n[71]*df1n[72]) +
(df1n[73]*df1n[74]*df1n[75]) + (df1n[76]*df1n[77]*df1n[78]))
)
Regards,
ikel
I’d use
lapply()to construct a list of indices for each of the(A*B*C)pieces. Then, pass those indices tosapply, extracting each set of elements fromdf1nand multiplying them withprod(). The rest is self-explanatory:EDIT: Now that I know that each element of
df1nis a length-215 vector, here’s the code I’d suggest instead: