Stefano Potter Stefano Potter -4 years ago 75
R Question

Matching filenames in loop

I want to loop through an array and match filenames to particular variables.

I am attempting to do so like this:

file.names = c("common", "08f13", "13f08")
for (f in file.names){
if grep("common", f) {
a=f
} else if grep("08f13", f){
b=f
} else
c=f
}


and if
common
is in the filename I want to assign it to the variable
a
and if
08
is in the filename assign it to
b
and so on. Based on the errors I am getting in r I think there is something wrong with the structure of my loop, or I am even using
grep
incorrectly.

My code returns this error:

Error: unexpected '}' in "}"

Answer Source
file.names = list.files(path, pattern=".prj")
for (f in file.names){
  if(grepl("common", f))  {
    a=f
  } else if(grepl("08", f)) {
    b=f
  } else {
    c=f
  }
}

Mistakes:

  1. Round brackets around if, else if blocks
  2. grep returns 1 / 0 which are integers and grepl returns TRUE / FALSE
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download