theamateurdataanalyst
theamateurdataanalyst

Reputation: 2834

how to extract columns in R to make multiple data frames?

I need help with a simple task. I have a dataframe 28x52 and I want to make several dataframes and rename each one. So it'll turn into 13 28x4 data frames. I know this probably involves a for loop and so I tried:

for(i in seq(1,52,4)){
  i <- data[,i:i+3]
} 

It didn't work though.

Upvotes: 2

Views: 640

Answers (3)

JEquihua
JEquihua

Reputation: 1227

what error did you get? i'm curious. Just elaborating on your answer you could do

# simulate 100x54 data matrix
data <- rnorm(54*100)

data <- matrix(data,100,54)

data <- as.data.frame(data)

# name variables and observations
for (i in 1:54){
  colnames(data)[i]<-paste("variable_",i,sep="")
}

for (i in 1:100){
  rownames(data)[i]<-paste("observation_",i,sep="")
}

# data structure
head(data)

# data.frame separation loop
counter=0
for(i in seq(1,52,4)){

  counter = counter + 1
  name <- paste("dataframe_",counter,sep="")
  assign(name,data[,i:(i+3)])
} 

# what is the class of created objects?
class(dataframe_1)

# check out first sub-data.frame 
head(dataframe_1)

You would get your info int the data frames: dataframe_1,...,dataframe_13

I didn't try this but it should work.

Upvotes: 0

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Here's one approach on a 3x9 source data.frame where we want to subset it into 3 3x3 data.frames.

m <- data.frame(matrix(1:27, ncol = 9))
lapply(split(sequence(ncol(m)), rep(1:3, each = 3)), function(x) m[, x])
# $`1`
#   X1 X2 X3
# 1  1  4  7
# 2  2  5  8
# 3  3  6  9
# 
# $`2`
#   X4 X5 X6
# 1 10 13 16
# 2 11 14 17
# 3 12 15 18
# 
# $`3`
#   X7 X8 X9
# 1 19 22 25
# 2 20 23 26
# 3 21 24 27

Create a sequence of the columns you want to extract, and create a list of your data.frames.

So, applied to something that replicates the structure of your data, you could use:

m <- data.frame(matrix(1:(28*52), ncol = 52))
lapply(split(sequence(ncol(m)), rep(1:(52/4), each = 4)), function(x) m[, x])

Upvotes: 2

Adrian
Adrian

Reputation: 694

Try using a list. For example, a quick and dirty way:

N <- 28*52
BigDataFrame <- data.frame(matrix(rnorm(N), nrow=28, ncol=52))
BigList <- NULL
Count <- 0
for (i in seq(1,49,4)) {
  Count <- Count + 1
  BigList[[Count]] <- BigDataFrame[,i:(i+3)]
}

Upvotes: 0

Related Questions