0

In an earlier post Benjamin and raymkchow helped me create new binary variables using a custom function for labeling diagnoses.

How to use custom function to create new binary variables within existing dataframe?

patient<-c("a","b","c")
diag_1<-c("8661", "2851","8651")
diag_2<-c("8651","8674","2866")
diag_3<-c("2430","3456","9089")

patient_db<-data_frame(patient,diag_1,diag_2,diag_3)

   patient  diag_1 diag_2 diag_3
1       a  8661   8651   2430
2       b  2851   8674   3456
3       c  8651   2866   9089

The function for creating the new binary variable is shown below:

 patient_db<-diagnosis_func(patient_db, "diag_1", "2851", "Anemia")

Which creates the following output:

  patient  diag_1 diag_2 diag_3  Anemia
1       a  8661   8651   2430      0
2       b  2851   8674   3456      1
3       c  8651   2866   9089      0

This time I'm trying to use a similar approach but instead of using a single diagnosis code ("2851") and name ("Anemia"), be able to read the codes and corresponding names from a small dataframe named ICD9_codes. For example:

code<-c("2851","7840","7245")
name<-c("anemia","fever","back pain")

ICD9_codes<-data_frame(code,name)

code     name
<chr>    <chr>
2851     anemia
7840     fever
7245     back pain

Runnig the function below using the the code and names colums from "ICD9_codes" dataframe column results in an error.

  patient_db<-diagnosis_func(patient_db, "diag_1",ICD9_codes$code, ICD9_codes$name)

Error:

 Error in `[[<-`(`*tmp*`, i, value = value) : no such index at level 1 

1 Answer 1

1

Try running your function in a loop for n number of times where n is the number of codes you have in your dataframe (ICD9_codes)

for (i in 1:nrow(ICD9_codes)){
patient_db = diagnosis_func(patient_db, "diag_1",ICD9_codes$code[i], ICD9_codes$name[i])
}
Sign up to request clarification or add additional context in comments.

2 Comments

Please explain what trying this will accomplish -- in other words, how this answers the question.
However, it would be nice to have the for loop inside the "diagnosis_func".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.