0

I have the following double loop:

indexnames = c(a, b, c, d, etc.) 
# with
# length(indexnames) = 87
# class(indexnames) = "character"
# (indexnames = indexes I want to add in a column)

files = c(aname, bname, cname, dname, etc.) 
# with
# length(files) = 87
# class(files) = "character"
# (files = name of files in the global environment)

Now I want to loop through the two list and add to the files[1] a column of name "index" with the input index[1]. I implemented this the following way:

for(i in files){
    for(j in indexnames){
      files[i] = cbind(Index = indexnames[j], files[i])
    }
}

When I run this, I get an error message of 50 or more warnings. What am I doing wrong? Appreciating any help, thanks.

gvncore
  • 33
  • 1
  • 6
  • 1
    make a reproducible example of the error. – s_baldur Nov 20 '19 at 11:18
  • 1
    What happens when you run `warnings()`? I can see that you have `files[i]` on both the left- and right hand side of `files[i] = cbind(Index = indexnames[j], files[i])` - that could be problematic I assume. Also, when you are looping as `for(i in files)`, `i` is not an index, but the actual values in `files` - so `files[i]` doesn't make sense I think. If you want to loop over the indices of `files` you can change the iteration as `for(i in seq_along(files))`. – Valeri Voev Nov 20 '19 at 11:19
  • Try `list(aname, bname, cname, dname, etc.)`, and in the loop `files[[i]] <- etc`. Maybe the same with the indexes. – Rui Barradas Nov 20 '19 at 11:23
  • I get the following error: In filenames[i] <- cbind(Index = indexnames[j], filenames[i]) : number of items to replace is not a multiple of replacement length The iteration is conducted through the list instead of the dataframes in my global environment. – gvncore Nov 20 '19 at 12:12

1 Answers1

0

You need to use get() and assign() functions to get the behavior you want.

Actually you don't have to use i or j in name elements when creating loops. It's easier to debug a loop if you name them in a more human readable way. Still let's look at your inner part of the loop.

files[i]

Given files is a vector, you cannot call a specific element by it's value this way (nor you'd want to, since it's just a vector with the name of objects). Instead make "i" cycle through a number vector 'for(i in 1:87)'

for (index in 1:87) {
  assign( files[i] , `[[<-`(get(files[i]), 'index', value = indexnames[i] ))
}

I found some help in this answer:

How to use `assign()` or `get()` on specific named column of a dataframe?