Writing an excel doc with a subset of my data in R. Currently the code is excessively long
@Duck from Stack overflow provided the answer. Pasting it here. Its is essentially writing a function:
library(r2excel)
#Data
sample_prime1 &lt;- 1:4
sample_prime2 &lt;- 10:14
sample_prime3 &lt;- 22:26
#Store in a list
List &lt;- list(sample_prime1,sample_prime2,sample_prime3)
#Function
myfun &lt;- function(wb,name,df) {
  # Create object
  sheet &lt;- createSheet(wb, sheetName = name)
  # Add headers
  xlsx.addHeader(wb, sheet, value=paste0('Validty for prime ',name))
  xlsx.addLineBreak(sheet, 1)
  xlsx.addTable(wb, sheet, data.frame(df),
                fontColor=&quot;darkblue&quot;, fontSize=14,
                rowFill=c(&quot;white&quot;, &quot;lightblue&quot;),
                startCol=2, 
                row.names=FALSE, 
                col.names = FALSE)
}
#Create workbook
filename &lt;- &quot;validitycheck.xlsx&quot; 
wb &lt;- createWorkbook(type=&quot;xlsx&quot;)
#Loop
#Vector for names
vnames &lt;- paste0('prime',1:length(List))
#Code
for(i in 1:length(List))
{
  myfun(wb,vnames[i],List[i])
}