我的数据框中有2列,我想要执行添加小时或添加天数等操作。
例如,我想检查我的date2是否在[date1; date1 + 30天]
我试过这个:
table(data$date1 <= data$date2 & data$date2 <= data$date1 + 30)
我收到了这个错误:
Error in data$date1 + 30 :
non-numeric argument to binary operator
我将日期格式的date1和date2转换为:
data$date1 <- substr(data$date1,1,16)
data$date1 <- format(data$date1, format="%Y-%m-%d %H:%M")
以下是我的数据主管:
id1 id2 date2 date1
1 CD0H 15741 2012/02/08 10:03 16/02/2015 16:22
2 CD00 15058 2011/05/19 09:25 07/05/2015 10:39
3 CHY0 15987 2011/01/20 11:58 06/02/2015 14:11
4 CTPO 15254 2010/09/29 12:45 01/04/2015 04:49
5 CDHY 15051 06/05/2015 15:01
6 CDJU 15035 17/04/2015 08:56
答案 0 :(得分:1)
或许转换为日期/时间对象不起作用:
def findAinD(cookies, cream): # assumes that cookies and cream can be treated as such in the for loop will fail otherwise
A1 = []
D1 = []
for mrow in range(1, Cookies.get_highest_row() + 1):
A1 += cookies['A' + str(mrow)]
D1 += cream['D' + str(mrow)]
A1.sort() # Alphabetical
D1.sort() # ^
for i, cookie in enumerate(A1): # Enumerate returns the index and the object for each iteration
A1[i] = D1.index(cookie) # If cookie IS in D, then A1[i] now contains the index of the first occurence of A[i] in D
# If cookie is not, then the result is -1, which is never an index,
# and we filter those out before round 2 (not shown)
return A1
班级仍然是“角色”:
library( lubridate )
data <- read.table( filename, header=TRUE, sep = ";" )
data$date1 <- substr(data$date1,1,16)
data$date1 <- format(data$date1, format="%Y/%m/%d %H:%M")
data$date2 <- substr(data$date2,1,16)
data$date2 <- format(data$date2, format="%d/%m/%Y %H:%M")
我按如下方式进行了转换:
> class(data$date1)
[1] "character"
这是更复杂的,但至少我们有时间和日期:
library( timeDate )
table <- read.table( filename, header=TRUE, sep = ";",
colClasses = c( "factor", "numeric", "character", "character" ))
data <- cbind( table[1:2],
apply( table[3], 2, FUN=function(x){ timeDate(x,format="%Y/%m/%d %H:%M") } ),
apply( table[4], 2, FUN=function(x){ timeDate(x,format="%d/%m/%Y %H:%M") } ) )
colnames(data) <- colnames(table)
答案 1 :(得分:0)
查看lubridate
库以了解日期和时间。
以下是使用lubridate添加30天的方法
library(lubridate)
ymd('2011-01-01') + days(30)
[1] "2011-01-31 UTC"
了解更多信息:
http://cran.r-project.org/web/packages/lubridate/vignettes/lubridate.html