2

I would like to loop through individual data frames (not in a list) and append a column to each df so that the appended column is a copy of column one in the original df.

For df x:

> x
  V1 V2 V3
1  1  2  3
2  1  2  3
3  1  2  2
4  1  2  2
5  1  1  1

Desired output would be:

> x
  V1 V2 V3 newCol
1  1  2  3  1
2  1  2  3  1
3  1  2  2  1
4  1  2  2  1
5  1  1  1  1

I tried using this loop:

filenames <- names(which(sapply(.GlobalEnv, is.data.frame)))
for(x in seq_along(filenames)){
  filenames[x]$newCol  <-   x[,1]
}

but error occurs:

Error in x[, 1] : incorrect number of dimensions

bartektartanus
  • 15,284
  • 6
  • 74
  • 102
USER_1
  • 2,409
  • 1
  • 28
  • 28
  • Okay, it appears you know that they should be in a list. Put them into a list. – Roland Aug 26 '14 at 12:31
  • @RichardScriven that answer does solve the problem I had but I don't think is a duplicate as the original question was about doing this with a for loop specifically. Which I realise isn't a very R way of doing this anyway. :-) – USER_1 Aug 26 '14 at 16:44

2 Answers2

2

Like this:

To variable filenames[x] assign value which is data frame with first column :)

assign(filenames[x], data.frame(get(filenames[x]),get(filenames[x])[,1]))
bartektartanus
  • 15,284
  • 6
  • 74
  • 102
1

Or, you could write

   for(i in seq_along(filenames)){
    assign(filenames[i], `[[<-`(get(filenames[i]),'newCol', 
                                value=get(filenames[i])[,1]))
   }

which is similar to the one below:

   for(i in seq_along(filenames)) {
   x <- get(filenames[i])
   x$newCol <- x[, 1]
   assign(filenames[i], x)
  }

  x1
 #  V1 V2 V3 newCol
 #1  1  2  3      1
 #2  1  2  3      1
 #3  1  2  2      1
 #4  1  2  2      1
 #5  1  1  1      1

The above could also written as:

data

  x1 <- structure(list(V1 = c(1L, 1L, 1L, 1L, 1L), V2 = c(2L, 2L, 2L, 
  2L, 1L), V3 = c(3L, 3L, 2L, 2L, 1L)), .Names = c("V1", "V2", 
 "V3"), class = "data.frame", row.names = c("1", "2", "3", "4", 
  "5"))

  x2 <- x1

  filenames <- c("x1", "x2")
akrun
  • 874,273
  • 37
  • 540
  • 662