在R中循环遍历数据帧长度的正确方法 [英] Proper way to loop over the length of a dataframe in R

查看:88
本文介绍了在R中循环遍历数据帧长度的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过大量的调试,令我沮丧的是:

After quite a bit of debugging today, to my dismay i found that:

for (i in 1:0) {
     print(i)
}

实际上分别在R中打印1和0.写时出现问题

Actually prints 1 and 0 respectively in R. The problem came up when writing

for (i in 1:nrow(myframe) {
     fn(i)
}

如果nrow(myframe)== 0,我原本打算根本不执行.正确的校正只是吗?

Which i had intended to not execute at all if nrow(myframe)==0. Is the proper correction just:

if (nrow(myvect) != 0) {
    for (i in 1:nrow(myframe) {
        fn(i)
    }
}

还是有一种更合适的方法来完成我在R中想要的工作?

Or is there a more proper way to do what I wanted in R?

推荐答案

您可以改用seq_along:

vec <- numeric() 
length(vec)
#[1] 0

for(i in seq_along(vec)) print(i)   # doesn't print anything

vec <- 1:5

for(i in seq_along(vec)) print(i)
#[1] 1
#[1] 2
#[1] 3
#[1] 4
#[1] 5

OP更新后进行编辑

df <- data.frame(a = numeric(), b = numeric())
> df
#[1] a b
#<0 rows> (or row.names with length 0)

for(i in seq_len(nrow(df))) print(i)    # doesn't print anything

df <- data.frame(a = 1:3, b = 5:7)

for(i in seq_len(nrow(df))) print(i)
#[1] 1
#[1] 2
#[1] 3

这篇关于在R中循环遍历数据帧长度的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆