R-在if循环中比较hhmm格式数据
我有一个名为 df 的数据框,如下所示。
ID HHmm
1 0840
2 0910
3 1050
4 1210
5 1230
我想添加第三列,类型,遵循以下规则:
for (k in 1 : nrow(df)){
if(df$HHmm >= 0860 & df$HHmm <= 1060){
df[k, 'type'] = "r1"
}else{
df[k, 'type'] = "c"
}
}
但我收到警告:
In if (df$HHmm >= 0860 & df$HHmm <= 1060) { ... :
the condition has length > 1 and only the first element will be used
并且我得到了不良结果,如下所示。
ID HHmm type
1 0840 r1
2 0910 r1
3 1050 r1
4 1210 r1
5 1230 r1
理想的结果应该如下所示
ID HHmm type
1 0840 c
2 0910 r1
3 1050 r1
4 1210 c
5 1230 c
有人能发现这里出了什么问题吗?如何在if循环中比较HHmm时间格式数据?
I have a dataframe named df, just as below.
ID HHmm
1 0840
2 0910
3 1050
4 1210
5 1230
I want to add a third column, type, that follows these rules:
for (k in 1 : nrow(df)){
if(df$HHmm >= 0860 & df$HHmm <= 1060){
df[k, 'type'] = "r1"
}else{
df[k, 'type'] = "c"
}
}
but I get the warning:
In if (df$HHmm >= 0860 & df$HHmm <= 1060) { ... :
the condition has length > 1 and only the first element will be used
and I got a undesirable results, just like below.
ID HHmm type
1 0840 r1
2 0910 r1
3 1050 r1
4 1210 r1
5 1230 r1
The desirable resultes should be like below
ID HHmm type
1 0840 c
2 0910 r1
3 1050 r1
4 1210 c
5 1230 c
Can anyone spot what's wrong here? How to compare HHmm time format data in if loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要定义索引
k
;例如df$HHmm[k]
。You need to define the index
k
; e.g.df$HHmm[k]
.您不需要(也不应该)使用循环在 R 中执行此类操作。它更慢、更冗长且更难以理解。
您只想创建一个名为
type
且值为“c”的列,然后将值“r1”分配给满足条件的列的子集:You do not need to (and should not) use a loop to do this kind of operation in R. It is slower, more verbose and harder to comprehend.
You just want to create a column called
type
with the value "c" and then assign the value "r1" to the subset of the column that meets your condition: