1

Hello i'm almost certain there must be a way to streamline this code, can someone help me out. I thought of a function or some form of apply? Thanks for the advice, ok so basically I have columns of data representing a answer key and a corresponding 1 or 0 for if the student got it correct, im trying to take that data and apply a 1 or 0 to a "score" column for 132 questions and 60 something students. This method seems to work for the first 42 but then i get a stack overflow, I tried breaking it into 3 blocks of the same code but now i'm just getting my "test" in all the columns.


dta$Score <- ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 1), dta$A1,
            ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 2), dta$A2,
           ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 3), dta$A3,
          ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 4), dta$A4,
         ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 5), dta$A5,
        ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 6), dta$A6,
       ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 7), dta$A7,
      ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 8), dta$A8,
     ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 9), dta$A9,
    ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 10), dta$A10,
   ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 11), dta$A11,
  ifelse((grepl("F19", dta$Semester) & dta$F19.Question == 12), dta$A12,
"test"))))))))))))
  • 1
    Hi @Jeffrey_Warren, Welcome to SO! Check out [`dplyr::case_when`](http://dplyr.tidyverse.org/reference/case_when.html) and [`dplyr::mutate`](http://dplyr.tidyverse.org/reference/mutate.html) as it may be of help. For example, check out [https://stackoverflow.com/questions/47612575/use-dplyr-case-when-programmatically](https://stackoverflow.com/questions/47612575/use-dplyr-case-when-programmatically) – Russ Thomas Aug 10 '20 at 01:33
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Describe the problem you are trying to solve in words rather than just asking someone to clean up your code. Depending on intent, they may be better approaches. – MrFlick Aug 10 '20 at 01:40
  • Thanks for the advice, ok so basically I have columns of data representing a answer key and a corresponding 1 or 0 for if the student got it correct, im trying to take that data and apply a 1 or 0 to a "score" column for 132 questions and 60 something students. This method seems to work for the first 42 but then i get a stack overflow, I tried breaking it into 3 blocks of the same code but now i'm just getting my "test" in all the columns. – Jeffrey Warren Aug 10 '20 at 02:07

0 Answers0