non-numeric argument to binary operator ERROR

I am very new to R so I end up with errors all the time, apologies in advance if this seems like a very basic question.
I have a variable 'patient_yearofbirth' in my dataset. To calculate the age of patients, I thought I could simply subtract 'patient_yearofbirth' from the current year '2020' . I used the following codes:

AZH$current_year<-c('2020') ##created current year variable so that age could be calculated
AZH_with_Age$Age<-AZH$current_year-AZH$patient_yearofbirth ##subtracted the two years to get age

But I am getting the following error: "Error in AZH$current_year - AZH$patient_yearofbirth : non-numeric argument to binary operator"

How should I go about it? What does this error imply?

Any help would be much appreciated.


Welcome to the RStudio community!

Lets look at an example:

#Some data
myData = data.frame(
  patient_yearofbirth = c("2001", "1999", "1989")
#>   patient_yearofbirth
#> 1                2001
#> 2                1999
#> 3                1989

#Look at the class
#> [1] "character"

#Change the class to an integer
myData$patient_yearofbirth = as.integer(myData$patient_yearofbirth)

#Look at the class
#> [1] "integer"

#Now calculate the age
myData$patient_age = 2020 - myData$patient_yearofbirth

#>   patient_yearofbirth patient_age
#> 1                2001          19
#> 2                1999          21
#> 3                1989          31

Created on 2021-01-20 by the reprex package (v0.3.0)

The reason you are getting the error, is because the patient_yearofbirth is of class character (i.e. text) and if you try to subtract text from text or even a number, R has no clue what to do, hence the error. By converting the column to the correct class (in this case integer), you can solve this problem.

Hope this helps,

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.