I would like to extract rows that correspond to a list, and save each output into separate excel files in R.

```
#sample data

x <- c("anna", "matt", "anna", "david", "anna", "jane")

data <- data.frame("name" = x,
                   "case ref" = letters[1:6])

```

| name | case ref |
| --- | --- |
| anna | a |
| matt | b |
| anna | c |
| david | d |
| anna | e |
| jane | f |

I have a name list that I want to extract from the data above

```
#name list

namelist <- c("matt", "david", "anna")

```

I have written a loop to do as such

```
for (i in namelist) {
answer <- data[is.element(data$name, i), ]
print(answer) 
}

```

However, I am stuck as to how to save each output into an excel file with corresponding name.

Below I figured how to save a file to each corresponding name

```
names(namelist) <- namelist
for (j in seq_along(namelist)) {
  write.xlsx(answer, paste(names(namelist)[j],".xlsx"))
  }

```

Basically I need to combine the above 2 for loops but I don't know how to work it.

```
names(namelist) <- namelist

for (i in namelist) {
  for (j in seq_along(namelist)) {
answer <- data[is.element(data$name, i), ] 
write.xlsx(answer, paste(names(namelist)[j],".xlsx"))
  }
}

```

The error now is all 3 files are saved with the first output.

```
Error in saveWorkbook(wb, file = file, overwrite = overwrite) : 
  File already exists!

```

What I require is such that first saved output with file name "matt.xlsx" and data is

| name | case ref |
| --- | --- |
| matt | b |

Last saved output with file name "anna.xslx" and the data is

| name | case ref |
| --- | --- |
| anna | a |
| anna | c |
| anna | e |

Thank you in advance!