Ran Tao
Ran Tao

Reputation: 311

Split a large file into equal rows in R

Here is my sample data

library(dplyr)
Singer <- c("A","B","C","A","B","D")
Rank <- c(1,2,3,3,2,1)
data <- data_frame(Singer,Rank)

I would like to split the data into three separate csv files, and each of them should have two rows. I tried to use the split function, but it did not word out as I expected.

d <- split(data,rep(1:2,each=2))

Upvotes: 1

Views: 522

Answers (1)

Axeman
Axeman

Reputation: 35177

Group first, then use do to apply the writing function to each pair of rows.

library(dplyr)
library(readr)

data %>% 
  group_by(g = ceiling(row_number() / 2)) %>% 
  do(write_csv(., paste0(.$g[1], '.csv')))

Upvotes: 3

Related Questions