-3

I want to analyze an eye data file in which I need to count fixations within each trial. Here is a sample of my data in which the 3rd and 4rd column are the x and y positions and the 8th column the fixation.

75      1 76498  797 637     0   3.313    3.320   1    0
76      1 76499  793 636     0   3.320    3.321   1    0
77      1 76500  788 637     0   3.292    3.308   1    0
78      1 76501  785 636     0   3.274    3.273   1    0
79      1 76502  781 636     0   3.257    3.265   1    0
80      1 76503  775 637     0   3.257    3.250   1    0
81      1 76504  760 641     0   3.247    3.236   0    0
82      1 76505  746 644     0   3.228    3.258   0    

I am trying to create a function that searches every fixation (indicated by a series of ones) until the fixation stops (indicated by a 0 in line82 for example) and then proceeds with the next fixation (the next 1 in column 8). For every trial (second column) I want to have for example 4 fixations each of which outputs the mean(x) and mean(y) and the length (as determined by nrow).

I would be happy if anyone knows a simple way of using a while or for loop since I have a hard time figuring this out. All the best,

Tim

4

1 回答 1

0

I think the interesting point here is how to solve it via R's vectorization techniques. Here is a rather straightforward and boring loop-based (non-vectorized) solution:

# get a list of the start and enpoints of all fixations
fixations <- vector(mode = "list")
inFixation <- FALSE
for (row in seq(nrow(df)) {
  # if we have no active fixation and we see a 1, add new fixation
  if (!isTRUE(inFixation) && df[row, 8] == 1) {
    fixations[[length(fixations) + 1]] <- c("start" = row, "end" = NA)
    inFixation <- TRUE
  }

  # if we have an active fixation and we see a 0, update end of current fixation
  if (isTRUE(inFixation) && (df[row, 8] == 0 || row == nrow(df))) {
    fixations[[length(fixations)]]["end"] <- row - 1
    inFixation <- FALSE
  }
}

# then you can get the mean x, y coordinates via
lapply(fixations, function(fixation) {
  c(
    "mean.x" = mean(df[seq(from = fixation["start"], to = fixation["end"], by = 1), 3],
    "mean.y" = mean(df[seq(from = fixation["start"], to = fixation["end"], by = 1), 4]
  )
})
于 2013-03-01T10:24:23.750 回答