T-T T-T - 4 days ago 6
R Question

How to include calculations in apply or rowsum?

I need to include some operations before summing the rows in my data frame. Here is an example:

df1 <- data.frame(
AC1Q = c(0.53, 0.57, 0.60, 0.51),
AC4Q = c(0.15, 0.12, 0.09,0.19),
AC2Q = c(0.09, 0.05, 0.07, 0.05),
AC3Q = c(0.23, 0.26, 0.23, 0.26)
)
df1
# AC1Q AC4Q AC2Q AC3Q
# 1 0.53 0.15 0.09 0.23
# 2 0.57 0.12 0.05 0.26
# 3 0.60 0.09 0.07 0.23
# 4 0.51 0.19 0.05 0.26


I want to get the row sums based on
(sin(2*pi*(AC1Q-0.25)) + sin(2*pi*(-AC4Q+0.25)) - sin(2*pi*(AC2Q+0.25)) - sin(2*pi*(AC3Q-0.25)))/4)
The result should be:

# 1 0.20
# 2 0.15
# 3 0.21
# 4 0.10


I am learning
apply
and tried
apply(df1, 1, function(x) (sin(2*pi*(df1$AC1Q-0.25)) + sin(2*pi*(-df1$AC4Q+0.25)) - sin(2*pi*(-df1$AC2Q+0.25)) - sin(2*pi*(df1$AC3Q-0.25)))/4)
but the result is wrong. I am not sure what I did wrong. I know I can always do the calculation for each column first, combine them into a data frame, and use
rowsum
But is there a more efficient way to do it?

Answer
apply(df1, 1, function(x)  (sin(2*pi)*(x["AC1Q"]-0.25) +
                            sin(2*pi)*(-x["AC4Q"]+0.25) - 
                            sin(2*pi)*(-x["AC2Q"]+0.25) - 
                            sin(2*pi)*(x["AC3Q"]-0.25))/4)
Comments