Ryan John
Ryan John

Reputation: 1430

Syntax for mapply vs for loop

My goal is to take a data set, 1. subset it and 2. print to .csv files

Example data

library(tidyverse)

mydata <- iris

Method to subset data:

z <- (split(mydata, (as.numeric(rownames(mydata))-1) %/% 50))
str(z)

I'm trying to use mapply and I can't get the syntax right.

mapply(write_csv(z, paste0(z,"file.csv"), col_names = FALSE)

If I were to code it with a for loop here's how I'd do it:

for(i in names(z)){
  write_csv(z[[i]], paste0(i,"file.csv"), col_names = FALSE)
}

How would I go about using mapply?

Upvotes: 0

Views: 130

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47330

Wth sapply this should work:

sapply(names(z),function(x){write_csv(z[[x]],paste0(x,"file.csv"), col_names = FALSE))

with mapply it would work this way

mapply(function(x,y){write_csv(x,paste0(y,"file.csv"), col_names = FALSE)},z,names(z))

Upvotes: 1

Related Questions