2017-06-06 6 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に設定されているのはなぜですか?
  • Rが自動的にfoo変数とその要素を新しいクラスに強制していることは明らかです。変数(foo、またはfoo[2]、またはfoo[[2]])のいずれも、earlydate変数のクラス("POSIXlt" "POSIXt")と一致しないのはなぜですか?
  • fooを正しく初期化すると、このタイプの値割り当てをサポートすることができる個々の要素を含むベクタ、リスト、または配列のようなものになるので、警告を発生させずに、このようなカウンタの直感的な動作?

答えて

1

まあ、POSIXltの裏には実際にはリストです。

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

割り当てが0になるのは、リストの最初の要素だからです。これは秒数であり、earlydateの場合は0です。 Rは、自動的にPOSIXltクラスにfoo変数を強要しない理由を私は本当に知らない

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

。私の推測は、一般的な日付への強制は難しいということです。 fooのすべてがNAの場合、ここで何をすべきかはっきりしていますが、要素の1つがすでに整数または文字列の場合はどうなりますか?しかし、最初にそれを強制するには、as.POSIXltを使用してください。

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

あなたはそれをやっているよ他に何によってInteger to POSIXltにこの答えで述べたように、あなたも、よりよい解決策であることをPOSIXctを使用して見つけることがあります。これは、起点からの秒数で日付を格納するため、その下にリストがないため、特定の種類の計算および格納に適しています。

関連する問題