Split a data frame

This tutorial explains how to split a data frame with R programming.
Sample Data
Create Sample Data
data <- read.table(text="X Y    Z
                   ID12   2012-06    566
                   ID1    2012-06  10239
                   ID6    2012-06    524
                   ID12   2012-07   2360
                   ID1    2012-07   13853
                   ID6    2012-07    2352
                   ID12   2012-08   3950
                   ID1    2012-08   14738
                   ID6    2012-08   4104",header=TRUE)
Split a data frame
mydt2 = split(data, data$Y)
Get first list element
mydt2[[1]]
Calculate mean on each list element
sapply(mydt2 , function(x) mean(x$Z))
Split a list into multiple data frames
for(i in 1:length(mydt2)) {
  assign(paste0("t.", i), mydt2[[i]])
}

R Tutorials : 75 Free R Tutorials

About Author:

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 7 years of experience in data science and predictive modeling. During his tenure, he has worked with global clients in various domains like banking, Telecom, HR and Health Insurance.

While I love having friends who agree, I only learn from those who don't.

Let's Get Connected: Email | LinkedIn

Get Free Email Updates :
*Please confirm your email address by clicking on the link sent to your Email*
Related Posts:
1 Response to "Split a data frame"
  1. dplyr is great for subsetting and calculating means, sd, min max etc. on subsetted data.

    ReplyDelete

Next → ← Prev