Replacing for loop with lapply