How to create a for in R with the indexes of a data frame

5

If I have a data.frame:

> dato<-as.data.frame(matrix(1:64,8,8,T))[-3,]
> dato
  V1 V2 V3 V4 V5 V6 V7 V8
1  1  2  3  4  5  6  7  8
2  9 10 11 12 13 14 15 16
4 25 26 27 28 29 30 31 32
5 33 34 35 36 37 38 39 40
6 41 42 43 44 45 46 47 48
7 49 50 51 52 53 54 55 56
8 57 58 59 60 61 62 63 64

How can I "call" the index vector (1, 2, 4, 5, 6, 7, 8)?

I want to use it as an index in for .

    
asked by anonymous 01.05.2018 / 16:15

2 answers

5

In addition to the excellent response from @ Marcus-Nunes, to automatically get% of% of your indices , you can use the data.frame :

dato <- as.data.frame(matrix(1:64, 8, 8, T))[-3, ]

# selectionar o nome das linhas e converter caracteres em numérico
rw <- as.numeric(row.names(dato))
rw
# [1] 1 2 4 5 6 7 8

Using row.names() in a loop rw :

for(i in rw) {
  print(i)
}
# [1] 1
# [1] 2
# [1] 4
# [1] 5
# [1] 6
# [1] 7
# [1] 8
    
01.05.2018 / 16:46
5

The key point here is to realize that all for in R is executed from an array of indexes. See the example below:

for (j in 1:5){
  print(j^2)
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

To do this loop, I implicitly created an array of indexes with the command 1:5 :

1:5
[1] 1 2 3 4 5

In particular, this vector starts at 1 and ends at 5 with an increment of 1. If I had explicitly done to create my for , I would get the same result:

indices <- c(1, 2, 3, 4, 5)
for (j in indices){
  print(j^2)
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

Therefore, for in R is defined over the positions of a vector. This vector may be as I see fit. Let us suppose that I wish to square not the first five positive integers, but the first five prime numbers. So I would have

indices <- c(2, 3, 5, 7, 11)
for (j in indices){
  print(j^2)
}
[1] 4
[1] 9
[1] 25
[1] 49
[1] 121

Notice how logic is the same? I just need to set my index vector correctly and make my counter vary in it. In your case, it would be something like

indices <- c(1, 2, 4, 5, 6, 7, 8)
for (j in indices){
  # comandos a serem executados
}

Of course the indices vector could have been defined in a less explicit way. For example, the

indices <- (1:8)[-3]
[1] 1 2 4 5 6 7 8

creates a vector with the first eight positive integers and removes the observation present in the third position.

Finally, there are several ways to solve the problem. The only feature that does not change is that R will always make the loop counter vary in the positions of a vector, from first to last.

    
01.05.2018 / 16:41