R-在if循环中比较hhmm格式数据

发布于 2025-01-14 08:40:24 字数 749 浏览 10 评论 0原文

我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

做个少女永远怀春 2025-01-21 08:40:24

您需要定义索引k;例如df$HHmm[k]

  for (k in 1:nrow(df)){
    if(df$HHmm[k] >= 0860 & df$HHmm[k] <= 1060){
      df[k, 'type'] = "r1"
    }else{
      df[k, 'type'] = "c"
    }
  }

You need to define the index k; e.g. df$HHmm[k].

  for (k in 1:nrow(df)){
    if(df$HHmm[k] >= 0860 & df$HHmm[k] <= 1060){
      df[k, 'type'] = "r1"
    }else{
      df[k, 'type'] = "c"
    }
  }
偷得浮生 2025-01-21 08:40:24

您不需要(也不应该)使用循环在 R 中执行此类操作。它更慢、更冗长且更难以理解。

您只想创建一个名为 type 且值为“c”的列,然后将值“r1”分配给满足条件的列的子集:

df$type  <- "c"
df$type[df$HHmm >= 0860 & df$HHmm <= 1060]  <- "r1"
df

# Output
#   ID HHmm type
# 1  1  840    c
# 2  2  910   r1
# 3  3 1050   r1
# 4  4 1210    c
# 5  5 1230    c

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:

df$type  <- "c"
df$type[df$HHmm >= 0860 & df$HHmm <= 1060]  <- "r1"
df

# Output
#   ID HHmm type
# 1  1  840    c
# 2  2  910   r1
# 3  3 1050   r1
# 4  4 1210    c
# 5  5 1230    c
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文