0

So I have two vectors (they are actually the starting rows and the ending rows for which my data presides in in another R object)

start=c(13,103,202,250)
end=c(102,201,249,300)

I am trying to create a loop where I can pull the data using the dataset_{#number}=read.table(text=data[start:end],sep=",",header=F)

n=1
for (i in start){
dataset_{n}=read.table(text=data[i:end[n]],sep=",",header=F)
n=n+1
}

Desired Output:

dataset_1
dataset_2
dataset_3
..

How do I tell the loop to create a brand new data set to save each contiguous block?? How do I tell R that {n} is not a string but part of the loop??

1 Answer 1

1

try assign:

for (i in 1:length(start))
  assign(paste0("dataset_", i), read.table(text=data[start[i]:end[i]], sep=",", header=F))

Answer to your comment:

To combine those datasets, use (a.) either the list approach (if you need the seperate frames, too):

# 1st, create list 
datasets <- mapply(function(from, to) read.table(text=data[from:to], 
                                                sep=",", 
                                                header=F), 
                  start, 
                  end, 
                  SIMPLIFY=FALSE)
# 2nd, combine elements into one data frame
dataset <- do.call(rbind, datasets) 

Or (b.) directly combine the data frames in your loop (if you just need the final combined data frame):

dataset <- data.frame()
for (i in 1:length(start))
  dataset <- rbind(dataset, read.table(text=data[start[i]:end[i]], 
                                       sep=",", 
                                       header=F))
Sign up to request clarification or add additional context in comments.

6 Comments

Or use a list like described here
Thank you Luke! Though was the assign function necessary? Could the loop have been with just paste("dataset_", i)=read.table(....)??
I guess better for me to ask is, why is when I tried the loop without the assign command did the loop not work? Sounds pretty intuitive that paste(x,y) would create the stringxy which would be assigned to read.table(..)
Assign let's you create new objects with dynamic names. paste(...)=read.table would try to assign a data frame (return value of read.table) to a string constant (return value of paste). This does not work.
Thanks luke. With the datsets that were generated from the loop I am trying to bind them all row wise. I am encountering the same problem of feeding the loop element into the string. Here is the loop. What am I missing?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.