How to get index in a loop in R

后端 未结 2 1873
逝去的感伤
逝去的感伤 2021-02-18 18:52

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/leng

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-18 19:26

    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)
    
    }
    

    Or use the which function.

    names <- c("name1", "name2")
    for(name in names){
    
        print(which(name == names))
    
    }
    

提交回复
热议问题