replace for loop with lapply.