bvowe
bvowe

Reputation: 3394

R IF statement with different selection

Ciao,

I have taken much feedback to create a reproducible example and my coding attempts.

Here is a sample data frame:

df <- data.frame("STUDENT" = 1:10, 
                 "test_FALL" = c(0, 0, 0, 0, 1, 1, 1, 0, 0, NA), 
                 "test_SPRING" = c(1, 1, 1, 1, 0, 0, 0, 1, 1, 1), 
                 "score_FALL" = c(53, 52, 98, 54, 57 ,87, 62, 95, 75, NA), 
                 "score_SPRING" = c(75, 54, 57, 51, 51, 81, 77, 87, 73, 69), 
                 "final_SCORE" = c(75, 54, 57, 51, 57, 87, 62, 87, 73, 69))

And sample code:

df$final_score[df$test_SPRING  == 1] <- df$score_SPRING
df$final_score[df$test_FALL == 1] <- df$score_FALL

And a second attempt at the code:

df$final_score1[(df$test_SPRING  == 1 & !is.na(df$test_SPRING))] <- df$score_SPRING
df$final_score1[(df$test_FALL == 1 & !is.na(df$test_FALL))] <- df$score_FALL

In my dataframe I have when a student took a test (test_SPRING test_FALL) and scores on tests (score_SPRING score_FALL). Basically I want to create the final_SCORE column which I include in the dataframe SUCH THAT if test_SPRING = 1, tot_score = score_SPRING else if test_FALL = 1, tot_score = score_Fall. I am unable to do so and cannot figure it out after many hours. Please offer any advice you may have.

Upvotes: 1

Views: 55

Answers (1)

akrun
akrun

Reputation: 887901

There are couple of ways to create the 'final_score'.

1) Using ifelse - Based on the example, the 'test' columns are mutually exclusive. So, we can use a single ifelse by checking the condition based on 'test_SPRING' (test_SPRING == 1). If it is TRUE, then get the 'score_SPRING' or else get 'score_FALSE'

with(df, ifelse(test_SPRING == 1, score_SPRING, score_FALL))
#[1] 75 54 57 51 57 87 62 87 73 69

2) Arithmetic - Number multiplied by 1 is the number itself and 0 gives 0 so multiply the 'score' columns with the corresponding 'test' columns, cbind and use rowSums

with(df,  NA^(!test_FALL & !test_SPRING) * rowSums(cbind(
                       score_SPRING * test_SPRING,  
                       score_FALL * test_FALL), 
                    na.rm = TRUE))
#[1] 75 54 57 51 57 87 62 87 73 69

Upvotes: 1

Related Questions