-5

I wanted to find the age in the database, I used this answer to solve the problem Get the difference between dates in terms of weeks, months, quarters, and years?

This code I used to find years

age <- function(dob, age.day = today(), units = "years", floor = TRUE) {
  calc.age = interval(dob, age.day) / duration(num = 1, units = units)
  if (floor) return(as.integer(floor(calc.age)))
  return(calc.age)
}

But when I am performing loop using for loop and trying to save value in new column in database customer, I am not able to do so.

for (i in customer$dateofbirth) {
  as.Date(i)
  customer$age <- age(i)
}

The result I am getting is same value in age column. Where I am going wrong?

Community
  • 1
  • 1
Hassan Qamar
  • 39
  • 1
  • 8
  • 1
    Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – zx8754 Jul 18 '16 at 07:42
  • I understand but I am doing course where they share there database in remote computer with no internet access. I will try to edit my question as much as I can. – Hassan Qamar Jul 18 '16 at 08:04

2 Answers2

2

If you want to use for loop, maybe this is helpful

for (i in customer$dateofbirth) 
 customer$age[i] <- age(as.Date(i))

@RHertel thanks for the comment age(as.Date(i))

user2100721
  • 3,557
  • 2
  • 20
  • 29
1
library(dplyr)
customer <- customer %>%
  rowwise() %>% 
  mutate(age = age(as.Date(dateofbirth)))
Maiasaura
  • 32,226
  • 27
  • 104
  • 108