Arrays R警告:“;要更换的项目数量不是更换长度的倍数”;似乎不正确
我有一个示例R脚本,如下所示:Arrays R警告:“;要更换的项目数量不是更换长度的倍数”;似乎不正确,arrays,r,list,vector,variable-assignment,Arrays,R,List,Vector,Variable Assignment,我有一个示例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)
# 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
>
#创建示例数据
日期嗯,POSIXlt
的幕后实际上是一个列表
> class(unclass(earlydate))
[1] "list"
> length(unclass(earlydate))
[1] 11
赋值为0,因为这是列表的第一个元素;这是秒数,对于earlydate
,它是0
> unclass(earlydate)[1]
$sec
[1] 0
我真的不知道为什么R不自动将foo
变量强制到POSIXlt
类中;我的猜测是,强迫约会通常是很难的。当所有foo
都是NA
时,这里很清楚该怎么做,但是如果其中一个元素已经是整数或字符串呢?但要先自己强制执行,请使用as.POSIXlt
foo <- rep(as.POSIXlt(NA), 5)
foo