0

So I have a small problem in R. I have multiple data sets (data0, data1,...) and I want to do the following:

data01 <- data0[1:6,]
data02 <- data0[7:12,]
data11 <- data1[1:6,]
data12 <- data1[7:12,]
data21 <- data2[1:6,]
data22 <- data2[7:12,]
data31 <- data3[1:6,]
data32 <- data3[7:12,]
...etc

I would like to do this in a for loop like so:

for(i in 1:(some high number)){
  datai1 <- datai[1:6,]
  datai2 <- datai[7:12,]
}

I've tried messing around with assign() and get(), however I cannot make it work. I found something that might work in this question, however the difference is that here the variable d should also change depending on the index. Any idea how I could make this work?

Fiurilli
  • 1
  • 2
  • 2
    Learn to use lists to collect related data. It's much easier to iterate over list elements. – Roland Jan 12 '18 at 14:16
  • @Roland qdread's solution worked, so I will use that in the meantime (the deadline is approaching). Will look into lists in the future, so thanks for the suggestion! – Fiurilli Jan 12 '18 at 14:25
  • 1
    No, don't use it. The next step will be much more difficult. – Roland Jan 12 '18 at 14:26
  • See also [How to make a list of data frames?](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207) – Gregor Thomas Jan 12 '18 at 14:30

2 Answers2

1

Here is a more R-like approach than using assign:

data1 <- data0 <- data.frame(x = 1:12, y = letters[1:12]) #some data

mylist <- mget(ls(pattern = "data\\d")) #collect free floating objects into list
#it would be better to put the data.frames into a list when you create them

res <- lapply(mylist, function(d) split(d[1:12,], rep(1:2, each = 6))) #loop over list and split each data.frame

The result is a nested list and it's easy to extract its elements:

res[["data1"]][["2"]]
#    x y
#7   7 g
#8   8 h
#9   9 i
#10 10 j
#11 11 k
#12 12 l
Roland
  • 117,893
  • 9
  • 163
  • 255
0

Assemble the variable names with paste() and then use get() and assign() as you suggest.

for (i in 1:10) {
  datai <- get(paste('data', i, sep = ''))
  assign(paste('data', i, '1', sep = ''), datai[1:6,])
  assign(paste('data', i, '2', sep = ''), datai[7:12,])
}
qdread
  • 2,331
  • 15
  • 28
  • Thanks this worked great! Could not find how to get those indices([1:6,]) working since including them in the paste() did not work. Retrieving the variable first fixes this and setting it to a placeholder works. – Fiurilli Jan 12 '18 at 14:16
  • 2
    No, this is bad practice and more difficult than it needs to be. Just use lists. – Roland Jan 12 '18 at 14:16
  • Agreed that it isn't the best practice, but it is illustrative to show how you can get the desired result. – qdread Jan 12 '18 at 14:37