简体   繁体   中英

Calculating summary scores using apply function and if else statement

I'm calculating two summary scores based on two 3-item scales. I'm calculating each like so:

tasksum <- paste("item",c(8,11,12), sep="")
all_data_2$summary_score_task <- apply(all_data_2[,tasksum], 1, sum, na.rm = FALSE)

activesum <- paste("item",c(14,21,25), sep="")
all_data_2$summary_score_act <- apply(all_data_2[,activesum], 1, sum, na.rm = FALSE) 

I would like to accomplish the following:

  1. for summary_score_task, in cases where "item8" is NA, I would like to calculate the summary score with the following expression: ((item11 + item12)/2)*3. In cases where it's not NA, I would like to continue to calculate the summary score the same way as above.

  2. for activity_score_act, in cases where "item21" is NA, I would like to calculate the summary score with the following expression: (2*ibr14 + ibr25). In cases where it's not NA, I would like to continue to calculate the summary score the same way as above.

I'm sort of new to R so I would appreciate some help with this. Thanks.

First, the function rowSums will handle the simple case of getting sums for every row (and more efficiently), though there is nothing wrong with using apply .

Second, to do the custom set of calculations you want to do, you can write your own anonymous function for use with apply that will do exactly the task you desire. apply with the margin argument set to 1 as you have will apply that function to each row of the input data. Without access to your data, here's an example:

set.seed(2)
all_data_2 <- data.frame(
  item8 = c(rnorm(48), NA, NA),
  item11 = rnorm(50),
  item12 = rnorm(50)
)

tasksum <- paste("item", c(8, 11, 12), sep = "")
  
all_data_2$summary_score_task <- 
  apply(all_data_2[,tasksum], 1, function(x) {
    # Note I am using the fact that I know the first element is item8
    if (is.na(x[1])) {
      ((x[2] + x[3])/2)*3
    } else {
      sum(x, na.rm = T)
    }
  })

You can accomplish your second task very similarly, I think. Examine your data after doing this and confirm it is doing what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM