Search code examples
rcurly-braces

What's wrong with the placement of my curly braces?


My program, written in R, has encountered an error with the placement of closing curly braces. The error occurs in the following code:

file_list <- list.files()

for (file in file_list){
    data <- read.fit(file)
    # if the merged dataset doesn't exist, create it
    if (!exists("cdata")){
        cdata<-with(data$record, data.frame (lat=position_lat, lon=position_long, speed=(speed/1000*60*60), alt=altitude, HR=heart_rate, time=timestamp)
    }

    # if the merged dataset does exist, append to it
    if (exists("cdata")){
        temp_cdata <-with(data$record, data.frame (lat=position_lat, lon=position_long, speed=(speed/1000*60*60), alt=altitude, HR=heart_rate, time=timestamp)
        cdata<-rbind(cdata, temp_cdata)
        rm(temp_cdata)
    }
}

I have looked over the code several times and do not see any cause for error, yet I keep getting the following:

Error: unexpected '}' in:
"    cdata<-with(data$record, data.frame (lat=position_lat, lon=position_long, speed=(speed/1000*60*60), alt=altitude, HR=heart_rate, time=timestamp)
    }"

# if the merged dataset does exist, append to it
if (exists("cdata")){
    temp_cdata <-with(data$record, data.frame (lat=position_lat, lon=position_long, speed=(speed/1000*60*60), alt=altitude, HR=heart_rate, time=timestamp)
    cdata<-rbind(cdata, temp_cdata)
Error: unexpected symbol in:
"    temp_cdata <-with(data$record, data.frame (lat=position_lat, lon=position_long, speed=(speed/1000*60*60), alt=altitude, HR=heart_rate, time=timestamp)
    cdata"
    rm(temp_cdata)
Warning message:
    In rm(temp_cdata) : object 'temp_cdata' not found
      }
    Error: unexpected '}' in "  }"
      }
    Error: unexpected '}' in "  }"

Solution

  • You can try this way after fixing cdata and temp_data parenthesis issue. No need to check cdata twice with exists(), use simple if-else

    file_list <- list.files()
    
    for (file in file_list){
      data <- read.fit(file)
        # if the merged dataset doesn't exist, create it
        if (!exists("cdata")){
          cdata<-with(data$record, data.frame (lat=position_lat, lon=position_long, speed=(speed/1000*60*60), alt=altitude, HR=heart_rate, time=timestamp))
        }else{
          #append to it
          temp_cdata <-with(data$record, data.frame (lat=position_lat, lon=position_long, speed=(speed/1000*60*60), alt=altitude, HR=heart_rate, time=timestamp))
          cdata<-rbind(cdata, temp_cdata)
          rm(temp_cdata)
        }
    }