Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

r - calculating number of days between 2 columns of dates in data frame

I have a data frame which has two columns of dates in the format yyyy/mm/dd. I am trying to calculate the number of days between these two dates for each observation within the data frame (and create a new variable with this number of days in it).

So far I have tried using the answer given here:

Calculate the number of weekdays between 2 dates in R

but editing the code so that it calculates number of total days rather than just the number of week days. This just came up with error saying:

Error in del/by : non-numeric argument to binary operator
In addition: Warning message:
In Ops.factor(to, from) : - not meaningful for factors

I have also attempted using this code:

finish <- as.Date(survey$date, format="%yyyy/%mm/%dd")
start <- as.Date(survey$tx_start, format="%yyyy/%mm/%dd")
date_diff<-as.data.frame(finish-start)

with the plan of using "cbind" or something equivalent to combine the data frame "days" to my data frame "survey" which has data in it.

Although this does not give me any errors, the observations within the "finish" and "start" objects are all "NA_real_", and the date_diff data frame therefore has all the observations listed as NA.

If someone could point me in the right direction that would be great! All the other question I have found do not seem to be dealing with dates within variables but as individual dates, and applying those techniques to variables hasn`t been working for me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Without your seeing your data (you can use the output of dput(head(survey)) to show us) this is a shot in the dark:

survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))

survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
                  as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
       date   tx_start date_diff
1 2012/07/26 2012/01/01  207 days
2 2012/07/25 2012/01/01  206 days

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...