2013-12-17 59 views
1

我正在處理包含日期的數據,並且有點麻煩。基本上我希望根據兩個現有日期和另一個變量計算一個新的日期,用於我的數據框中的所有行。例如,我希望能夠從Date1中減去10天,或者計算Date1和Date2中間的日期等。但是,將新計算的日期添加到數據框時,我無法理解類分配。樣本數據框中:在R中執行算術的日期難度很大

# Uncomment to clear your session... 
# rm(list = ls(all = TRUE)) 
tC <- textConnection("StudyID Date1 Date2 
C0031 2-May-09 12-Jan-10 
C0032 7-May-09 30-Apr-10") 
data <- read.table(header=TRUE, tC) 
close.connection(tC) 
rm(tC) 

#CONVERTING TO DATES  
data$Date1 <- with(data,as.Date(Date1,format="%d-%b-%y")) 
data$Date2 <- with(data,as.Date(Date2,format="%d-%b-%y")) 

現在,這裏是我的問題開始

class(data[1, "Date2"] - 10) # class is "Date". So far so good. 
data[1, "newdate"] <- (data[1, "Date2"] - 10) 
class(data[1, "newdate"]) # class is now "numeric"... 

並試圖

data[1, "newdate"] <- as.Date(data[1, "Date2"] - 10) 
class(data[1, "newdate"]) # doesn't help. Class still "numeric"... 

只是不明白爲什麼當分配給數據

+0

你試過'數據$ newdate < - 數據$日期1 - 10'?我認爲問題在於回收單一價值。由於列的長度必須相同,因此您的單數日期值將循環使用以匹配data.frame中的行數。我假設(我會檢查)回收帶屬性,從而將日期轉換爲它們的數字形式。 –

回答

0

該問題是由於您的矢量剝離屬性的回收。正如我在評論中所述,使用例如data$newdate <- data$Date1 - 10創建整個色譜柱而不回收載體,因此保留了諸如Date之類的屬性。考慮下面的示例性的玩具例子:

# Simple vector with an attribute 
x <- 1:3 
attributes(x) <- list(att = "some attributes") 
x 
#[1] 1 2 3 
#attr(,"att") 
#[1] "some attributes" 

# Simple data.frame with 3 rows 
df <- data.frame(a = 1:3) 

# New column using first element of vector with attributes 
df$b <- x[1] 

# It is recycled to correct number of rows and attributes are stripped 
str(df$b) 
# int [1:3] 1 1 1 

# Without recycling attributes are retained 
df$c <- x 
str(df$c) 
# atomic [1:3] 1 2 3 
# - attr(*, "att")= chr "some attributes" 

# But they all look the same... 
df 
# a b c 
#1 1 1 1 
#2 2 1 2 
#3 3 1 3 

並將您的數據..

attributes(data$Date1) 
# $class 
# [1] "Date" 
+1

謝謝你們提供了兩個很好的答案,一個是實用的,另一個是解剖潛在的行爲。非常感激,現在已經不知情! – marcel

2

該數值變爲數字問題是由於不存在列newdate的組合^ h分配一個值:

# create a single value in a new column 
data[1, "newdate"] <- data[1, "Date2"] - 10 
class(data[1, "newdate"]) # numeric 

# create the whole column 
data[ , "newdate2"] <- data[1, "Date2"] - 10 
class(data[1, "newdate2"]) # Date 

# create a column of class Date before assigning value 
data[ , "newdate3"] <- as.Date(NA) 
data[1, "newdate3"] <- data[1, "Date2"] - 10 
class(data[1, "newdate3"]) # Date 

順便說一句,與Date對象進行數學運算時,你不需要as.Date