2016-07-18 42 views
-5

我想找到在数据库中的年龄,我用这个答案来解决问题Get the difference between dates in terms of weeks, months, quarters, and years?如何在for循环中在R中添加新列?

此代码我用来寻找年

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) 
} 

但是,当我使用for循环,并试图进行循环为了在数据库客户的新列中节省价值,我无法这样做。

我得到的结果在年龄栏中是相同的值。我哪里出错了?

+1

请阅读有关的信息[如何提出一个很好的问题( http://stackoverflow.com/help/how-to-ask)以及如何给出[可重现的例子](http://stackoverflow.com/questions/5963269)。这会让其他人更容易帮助你。 – zx8754

+0

我明白,但我正在做的课程,他们在远程计算机中共享那里没有互联网访问数据库。我会尽可能地编辑我的问题。 –

回答

1
library(dplyr) 
customer <- customer %>% 
    rowwise() %>% 
    mutate(age = age(as.Date(dateofbirth))) 
+0

未来的“字符串不是标准的umambigious格式” –

+0

如果没有一些示例数据,则无法进一步排除故障。看到你的问题中的评论。 – Maiasaura

2

如果你想使用for循环,也许这是有帮助的

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

@RHertel感谢您的评论age(as.Date(i))

+1

@RHertel:感谢您的评论。我忽略了这一点。 – user2100721

+1

不客气。不过,我不确定这是否有效。 OP没有提供可重复的例子。 – RHertel