Neil Neil - 1 year ago 72
R Question

how to split a dataframe to specific number of rows in if loop in R

I am writing a function to send emails to my clients in R. I am using mailR package to do so,but my service provider only allows me to send 100 emails an hour. What I want to do is, if suppose my email list contains 270 email addresses,I want to spilt that into

chunk1=100 , chunk2 = 100 & chunk3 = 70
Then it should send out emails to first chunk then wait for an hour and then chunk2 and so on.
This is my function looks like.

email <- function(dataframe,city,date){
dataframe$registrant_email <- tolower(dataframe$registrant_email)
dataframe_city <- dataframe[dataframe$registrant_city == city & dataframe$create_date == date, ]
# Removing NA's and blank email ids
dataframe_city <- dataframe_city[!($registrant_email)|dataframe_city$registrant_email==""), ]
# Removing duplicate email ids
dataframe_city <-dataframe_city[!duplicated(dataframe_city$registrant_email),]
emails <- as.vector(dataframe_city$registrant_email)
if(length(emails) > 100){

# divide the vector into chunks of 100

} else{send_email(emails}


I need a help in
if loop
how can I write the splitting part into chunk of 100 and then call a
function wait for an hour and so on.

Answer Source

You can split your email-vector into a list with a one-liner:

mailinglist <- split(emails, ceiling(seq_along(emails)/100))

Then you could delay the execution of the mailing by something like:

for(i in mailinglist) {

I tested the loop with a simple mean() call and it worked, but you should test it yourself with a lower time and by sending mails to yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download