2017-06-06 64 views
2

我有一個爲R腳本,看起來像這樣:R警告:「項目,以取代的數目不替換長度的倍數」似乎不正確

# Create example data 
date <- c("11/09/2016", "11/02/2016", "11/16/2016", "11/23/2016") 
column_two <- c(4, 2, 3, 4) 
# Populate a data frame and make sure the dates have the correct class 
mydata <- data.frame(date, column_two) 
mydata$date <- strptime(mydata$date, format="%m/%d/%Y") 

print("The contents of mydata are:") 
print(mydata) 

# Create a dummy list (or vector, or array, or what is it?) 
foo <- rep(NA, 5) 
print("foo is initialized to:") 
print(foo) 
print("The class of foo is:") 
print(class(foo)) 

earlydate <- min(mydata$date) 
print(sprintf("Earliest date is: %s", earlydate)) 
print("The class of earlydate is:") 
print(class(earlydate)) 
print(sprintf("Length of earliest date is: %d", length(earlydate))) 
print(sprintf("Length of foo[2] is: %d", length(foo[2]))) 

# Attempt to set one variable equal to another 
foo[2] <- earlydate 

print("After assignment, foo looks like this:") 
print(foo) 
print("Now the classes of foo, foo[2], and foo[[2]] are:") 
print(class(foo)) 
print(class(foo[2])) 
print(class(foo[[2]])) 

從腳本打印輸出如下所示:

> source("test_warning.R") 
[1] "The contents of mydata are:" 
     date column_two 
1 2016-11-09   4 
2 2016-11-02   2 
3 2016-11-16   3 
4 2016-11-23   4 
[1] "foo is initialized to:" 
[1] NA NA NA NA NA 
[1] "The class of foo is:" 
[1] "logical" 
[1] "Earliest date is: 2016-11-02" 
[1] "The class of earlydate is:" 
[1] "POSIXlt" "POSIXt" 
[1] "Length of earliest date is: 1" 
[1] "Length of foo[2] is: 1" 
[1] "After assignment, foo looks like this:" 
[[1]] 
[1] NA 

[[2]] 
[1] 0 

[[3]] 
[1] NA 

[[4]] 
[1] NA 

[[5]] 
[1] NA 

[1] "Now the classes of foo, foo[2], and foo[[2]] are:" 
[1] "list" 
[1] "list" 
[1] "numeric" 
Warning message: 
In foo[2] <- earlydate : 
    number of items to replace is not a multiple of replacement length 
> 

我有這麼多的問題:

  • 爲什麼我得到一個警告,當foo[2]earlydate顯然是相同的長度?
  • 爲什麼foo [2]的值設置爲0而不是值爲earlydate
  • 很明顯,R會自動將foo變量及其元素強制爲新的類;爲什麼這些類別中的任何一個(foofoo[2]foo[[2]])似乎都與earlydate變量的類別("POSIXlt" "POSIXt")相匹配?
  • 我該如何正確初始化foo,以便它成爲一個向量,列表或類似數組的東西,其中包含能夠支持這種類型值賦值的單獨元素,而不會引發這種警告並導致這種反直覺行爲?

回答

1

那麼,幕後的POSIXlt實際上是一個列表。

> class(unclass(earlydate)) 
[1] "list" 
> length(unclass(earlydate)) 
[1] 11 

賦值爲0,因爲這是列表的第一個元素;它是秒數,earlydate爲0。

> unclass(earlydate)[1] 
$sec 
[1] 0 

我真的不知道爲什麼R不自動要挾foo可變進POSIXlt類;我的猜測是,對日期的強制通常很難。很明顯,在fooNA的情況下要做什麼,但如果其中一個元素已經是整數或字符串呢?但首先要自己強制使用,請使用as.POSIXlt

foo <- rep(as.POSIXlt(NA), 5) 

取決於你會用它做什麼其他,你也可能會發現使用POSIXct是更好的解決方案,在這個答案討論Integer to POSIXlt。它將日期存儲爲從原點開始的秒數,因此不是下面的列表,因此更適合於某些類型的計算和存儲。

相關問題