0

I want to a go through 'paragraphs' a list of however many paragraphs and save each individual one as a new variable and tried writing this code block and am getting the following errors:

for (value in paragraphs) {
     nam <- paste("p", value, sep = ".")
     value <- assign(nam, 1:value)
}

Error in 1:value : NA/NaN argument
In addition: Warning message:
In assign(nam, 1:value) : NAs introduced by coercion

Any advice as to where to go from here?

djc1223
  • 45
  • 1
  • 6
  • Welcome to SO! Please provide a sample of your data with `dput`; see (here)[https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example] – starja Jun 16 '20 at 15:58
  • I would strongly suggest you reconsider using `assign()`. Creating a bunch of variables that have indexes in their names is not really a good practice. It's much easier to work with the data in R if you store these values in a (named) list. Then you can easily apply functions to them. Why do you think you need these are separate variables? – MrFlick Jun 16 '20 at 16:05

1 Answers1

0

I think you are trying to create a number of variables called p1, p2, p3 etc, each with the corresponding paragraph written to it. In that case, the following should work:

for (value in seq_along(paragraphs)) {
     nam <- paste("p", value, sep = ".")
     value <- assign(nam, paragraphs[value])
}

However, it is not a great idea to write a bunch of variables to the global workspace, and it would be better if the paragraphs were all in a named list. You say they are in a list already, but it's not clear if you mean a an actual R list or just a vector. If they are in a list already, you could do:

p <- setNames(paragraphs, paste0("p", seq_along(paragraphs)))

This would allow you to access each paragraph as p$p1, p$p2 etc.

If the paragraphs are in a vector rather than a list, you could do

p <- setNames(as.list(paragraphs), paste0("p", seq_along(paragraphs)))

to get the same result.

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • This worked! If you don't mind me askign what exactly does the 'seq_along()' method do? – djc1223 Jun 16 '20 at 16:07
  • @djc1223 The `seq_along` function creates a sequence starting at one and stopping at the length of the supplied object, a bit like `1:length(paragraphs)`. – Allan Cameron Jun 16 '20 at 16:09
  • Great, this helps a lot, and I had them stored in a vector, sorry about the weird phrasing. Is not a great idea to save a bunch of variables to the global workspace because of data loss or just bad naming conventions? – djc1223 Jun 16 '20 at 16:15
  • @djc1223 it clutters your workspace with lots of objects, making it difficult to find what you need, and runs the risk of overwriting other variables. Also, having all the paragraphs in a single list lets you apply functions to all of them at once instead of having to run a function on each variable separately. – Allan Cameron Jun 16 '20 at 16:18