在R中我试图添加一些只有几小时的额外列。
我有一个名为Time的列:
09:30
09:45
10:00
10:40
我想要一个额外的专栏:
时间:
9
9
10
10
列时间来自“因子”类型。当我尝试这个时:
library(lubridate)
data$hour <- hour(hm(c(data$Time)))
我收到警告:
Warning message:
In .parse_hms(..., order = "HM", quiet = quiet):
some strings failed to parse
我不明白为什么会出错。有人能帮我吗?
答案 0 :(得分:0)
从c()
移除hour(hm(c(data$Time)))
来电。
通过将data$Time
与c()
包装在一起,就会迫使因子丢弃其属性。这只会导致其整数值,并且在传递给hm()
时无法解析。
x <- factor(c("09:30", "09:45", "10:00", "10:40"))
## everything is fine
x
# [1] 09:30 09:45 10:00 10:40
# Levels: 09:30 09:45 10:00 10:40
## wrapped with c() --> attributes dropped
c(x)
# [1] 1 2 3 4
## wrapped with c() --> attributes dropped --> parsing fails
lubridate::hm(c(x))
# [1] NA NA NA NA
# Warning message:
# In .parse_hms(..., order = "HM", quiet = quiet) :
# Some strings failed to parse
## remove c() --> everything is fine
lubridate::hm(x)
# [1] "9H 30M 0S" "9H 45M 0S" "10H 0M 0S" "10H 40M 0S"
所以只需将代码更改为
即可data$Time <- hour(hm(data$Time))