Maharero Maharero - 1 year ago 97
R Question

Need assistance with understanding R for loop error: unexpected '}' in " }"

Just to give some background first:

I currently have 2 data frames (giraffe, leaf) and both of them share the column 'key', where the elements in the leaf data frame are a subset of giraffe. What I needed to do is compare the two data frames and when there are matching elements in both data frames in the 'key' column, the string 'leaf' will be input into another column (project) in the giraffe data frame inside the same row as the matching 'key' element. I've taken the following approach however it seems I have made a small error somewhere and after searching online, I still don't know what it is:

Truth_vector <- is.element((giraffe[,1]),(leaf[,1]))
#returns a vector with 3000 elements, most are FALSE except for where the element inside 'key' is present in both data frames

i=1
for (i in 1:length(giraffe[,1])) {
if Truth_vector[i] == TRUE {
giraffe[i,5] <- 'leaf'
}
i = i+1
}

Error: unexpected '}' in "}"

Answer Source

You have a couple issues. First, the if criteria needs to be in parentheses, and secondly you don't need to increment i yourself. This should suffice:

for (i in 1:length(giraffe[,1])) {
  if (Truth_vector[i] == TRUE) {
   giraffe[i,5] <- 'leaf'
  }
}

Of course, this would do it too:

giraffe[which(Truth_vector),5] <- 'leaf'

(assuming Truth_vector is not longer than the number of rows in giraffe)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download