Home > Software engineering >  Appending to a vector in a for-loop of a specific value from a data frame
Appending to a vector in a for-loop of a specific value from a data frame

Time:12-16

I've recently ran into a problem with a pretty simple task. So, I have a data frame called tissue.position which contains an x-position (in the 5th column) and a y-position (in the 6th column). I only want to extract specific elements with specific index positions, and the indexes of the positions of elements that I need to extract are stored in a vector called index_of_matched. I would like to extract the elements with these specific indices and there corresponding x- and y-positions. I have the following code:

x_position <- c()
y_position <- c()

for (i in length(index_of_matched)) {
  a = index_of_matched[i]
  x_position <- append(x_position, as.vector(tissue.position[a,5]))
  y_position <- append(y_position, as.vector(tissue.position[a,6]))
}

spatial.data <- data.frame(x_position,y_position)

spatial.data is the name of the data frame where I store the specifically chosen x- and y-coordinates. However, when I run the code I somehow only get one single element for x- and y-coordinates respectively. When I check the number of indices that I want to extract it is about 3700, which means that something is wrong. The output seems to be a sum of the coordinates. Here is the output:

x-position  y-position
22117   19328       

Where did I go wrong in my code? Thank you for any help in advance!

CodePudding user response:

The main thing wrong is that i in length(index_of_matched) is just one number, not iterating through a range. A corrected version would be i in seq_along(index_of_matched).

However, using for loops like this is non-idiomatic, since R has more expressive ways of accomplishing the same thing:

x_position <- tissue.position[index_of_matched, 5]
y_position <- tissue.position[index_of_matched, 6]

spatial.data <- data.frame(x_position,y_position)

or, since tissue.position is already a data.frame, simply

spatial.data <- tissue.position[index_of_matched, c(5,6)]
  • Related