0

I have many data frames id.1, id.2, ... ,id.21 and in each of which I want to extract 2 data points: id.1[5,4] and id.1[10,6], id.2[5,4] and id.2[10,6], etc. The first data point is a date and the second data point is a integer.

I want to export this list to obtain something like this in an .csv file:

        V1          V2
1    5/10/2016      1654395291
2    5/11/2016      1645024703
3    5/12/2016      1763825219

I have tried

 x=c(for (i in 1:21) {
            file1 = paste("id.", i, "[5,4]", sep="")}, for (i in 1:21) {
            file1 = paste("id.", i, "[10,6]", sep="")})
 write.csv(x, "x.csv")

But this yields x being NULL. How can I go about getting this vector?

  • 1
    See the [this post](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) on working with data.frames in lists. It makes operations such as the one you are attempting much easier. – lmo Jun 12 '16 at 15:15

1 Answers1

0

Your problem is that a for loop doesn't return anything in R. So you can't use it in a c statement as you did. Use an [sl]apply construct instead.

I would first make a list containing all the data frames:

dfs <- list(id.1, id.2, id.3, ...)

And iterate over it, something like:

x <- sapply(dfs, function(df) {
  return(c(df[5,4], df[10,6]))
})

Finally you need to transpose the result and convert it into a data.frame if you want to:

x <- as.data.frame(t(x))
Calimo
  • 6,230
  • 3
  • 31
  • 52
  • Thank you. In reality, my data frames `id.1`, `id.2`, etc, go to a large number, say 1500. Is there a way to get `list(id.1, ... , id.1500)` without having to type it in? – Florian Richard Jun 12 '16 at 15:47
  • Use the `get` function – Calimo Jun 12 '16 at 15:50
  • @FlorianRichard See the link I posted in my comment to your question. – lmo Jun 12 '16 at 15:56
  • @Imo: I see. However, I am getting the names `id.1`, `id.2`, etc from the assign function because my files originally have odd names (such as 0nwn05ua.xls or 2gof3vo2.xls): `files = list.files(pattern="*.xls")` `for (i in seq_along(files)) { assign(paste("id", i, sep = "."), read.xlsx(files[i],1,as.data.frame=TRUE, header=FALSE, stringsAsFactors=FALSE, na.strings=" ")) }` so each file is assigned an `id.[i]` name but I don't know how to retrieve this in the `list()` function. – Florian Richard Jun 12 '16 at 18:14
  • Why do you assign them to a variable rather than saving them in a list? – Calimo Jun 12 '16 at 18:59
  • @FlorianRichard btw this is described in plenty of detail in this answer to the question that lmo referred to earlier: http://stackoverflow.com/a/24376207/333599 – Calimo Jun 12 '16 at 19:05
  • @Calimo Indeed. Didn't get passed the first answer. Thank you. – Florian Richard Jun 12 '16 at 19:23