如何在R中的循环中获取索引 [英] How to get index in a loop in R

查看:162
本文介绍了如何在R中的循环中获取索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符类型的向量,其中包含所有名称列表.

I have a vector of character type which has all the list of names.

所以我要遍历每个名​​称并执行一些操作.此循环不是基于索引/长度(我想保持这种方式).

So I'm looping through each name and peforming some actions. This loop is not based on the index/length (and I want to keep it this way).

但是,如果我要在循环中访问索引值,该如何获取它.

However, if I want to access the index value in the loop how do I get it.

例如:

names <- c("name1", "name2")

for(name in names){

#do something
print(name)

#here how would I get the index number? like 1, 2 etc?

}

推荐答案

您可以执行以下操作,即从字面上获取i值.

You can do something like this, which is literally getting the i value.

names <- c("name1", "name2")
i<-0
for(name in names){
    i<-i+1
    print(i)

}

或更改循环以使用数字索引

Or change the loop to use a numeric index

names <- c("name1", "name2")
for(i in 1:length(names)){
    print(i)

}

或使用which功能.

names <- c("name1", "name2")
for(name in names){

    print(which(name == names))

}

这篇关于如何在R中的循环中获取索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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