'x'在R中通过cut()函数将时间间隔转换为字符串标签时必须是数字错误
'x' must be numeric error when converting time interval to string labels by cut() function in R
我有一个列 'Incident_Time' 表示 R 数据框中的时间。
当我在列上调用 str() 函数时,它显示类似这样的内容
str(crime_data$Incident_Time)
Factor w/ 1439 levels "00:01:00","00:02:00",..: 840 945 1140 981 1260 969 1020 840 980 765 ...
我想将此列转换为字符串类型,如果时间小于 12:00:00,则应将其修改为字符串 "morning",如果时间介于 12:00:00 之间和 6:00:00 ,它是 "daylight" 等等。
我输入了以下命令:
time.tag <- chron(times=c("00:00:00", "06:00:00", "12:00:00", "18:00:00", "23:59:59"))
labels <- c("Early Morning", "Morning", "Evening", "Night")
crime_data$Incident_Time_Range <- cut(crime_data$Incident_Time, breaks = time.tag, labels, include.lowest = TRUE )
然后出现如下错误:
Error in cut.default(crime_data$Incident_Time, breaks = time.tag, labels, :
'x' must be numeric
请帮我找出问题所在。谢谢。
未验证,因为没有示例数据,但您不应将事件时间作为一个因素。转换为时间:
crime_data$Incident_Time <- chron(times=as.character(crime_data$Incident_Time))
然后运行您现有的代码
提供一个完整的例子。
示例数据
sampletime<-chron(times=as.character(as.ITime(Sys.time()+sample(86400,100))))
不需要对代码进行任何修改,但在我使用 chron
将 sampletime
转换为 class times
之前它不会工作。我相信如果您的数据不一样, cut 将不起作用 class
.
cut(sampletime, breaks = time.tag, labels, include.lowest = TRUE )
[1] Early Morning Evening Evening Evening
[5] Morning Night Evening Night
[9] Night Morning Early Morning Early Morning
[13] Evening Early Morning Morning Early Morning
[17] Evening Morning Early Morning Evening
....
我有一个列 'Incident_Time' 表示 R 数据框中的时间。
当我在列上调用 str() 函数时,它显示类似这样的内容
str(crime_data$Incident_Time)
Factor w/ 1439 levels "00:01:00","00:02:00",..: 840 945 1140 981 1260 969 1020 840 980 765 ...
我想将此列转换为字符串类型,如果时间小于 12:00:00,则应将其修改为字符串 "morning",如果时间介于 12:00:00 之间和 6:00:00 ,它是 "daylight" 等等。
我输入了以下命令:
time.tag <- chron(times=c("00:00:00", "06:00:00", "12:00:00", "18:00:00", "23:59:59"))
labels <- c("Early Morning", "Morning", "Evening", "Night")
crime_data$Incident_Time_Range <- cut(crime_data$Incident_Time, breaks = time.tag, labels, include.lowest = TRUE )
然后出现如下错误:
Error in cut.default(crime_data$Incident_Time, breaks = time.tag, labels, : 'x' must be numeric
请帮我找出问题所在。谢谢。
未验证,因为没有示例数据,但您不应将事件时间作为一个因素。转换为时间:
crime_data$Incident_Time <- chron(times=as.character(crime_data$Incident_Time))
然后运行您现有的代码
提供一个完整的例子。
示例数据
sampletime<-chron(times=as.character(as.ITime(Sys.time()+sample(86400,100))))
不需要对代码进行任何修改,但在我使用 chron
将 sampletime
转换为 class times
之前它不会工作。我相信如果您的数据不一样, cut 将不起作用 class
.
cut(sampletime, breaks = time.tag, labels, include.lowest = TRUE )
[1] Early Morning Evening Evening Evening
[5] Morning Night Evening Night
[9] Night Morning Early Morning Early Morning
[13] Evening Early Morning Morning Early Morning
[17] Evening Morning Early Morning Evening
....