-1

I want to write a for loop that "grabs" data from already existing data frames, and stores them in a vector. However, I cannot determine how to use the paste function to get R to access column ohm.2 row 37 in the dataframe.

Here is my best attempt:

for(i in 6:18){
  vec = numeric(4)
  for(n in 1:4){
    path <- paste("dat_",i,"_",n,"$ohm.2[37]")
    val <- path
    vec[n] <- val
  }
  assign(paste0("dat_",i),vec)
}

In this attempt, I get vectors correctly named, but instead of storing the number in row 37 column ohm.2 for each dataframe, it just stores the text:

[1] "dat_ 10 _ 1 $ohm.2[37]" "dat_ 10 _ 2 $ohm.2[37]"
[3] "dat_ 10 _ 3 $ohm.2[37]" "dat_ 10 _ 4 $ohm.2[37]"
  • `paste` is vectorized, you don't need a loop. It is also not clear why you need to create multiple objects in the global env – akrun Jun 25 '18 at 20:16
  • 1
    You assign `vec` as a number, but then assign a string to it ... there are several problems with this code, including @akrun's mention of vectorization and the double-`for` loop. I suggest you [provide some sample data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) (perhaps 3-4 rows) and the expected output, and perhaps then we can help you with your code. – r2evans Jun 25 '18 at 20:21
  • 2
    Where did all these `dat_10_3` data frames come from? Things would be much easier in R if they were all in a list. Having a bunch of similarly named variables that differ by an index number is a sign that you're not doing things the R-way. – MrFlick Jun 25 '18 at 20:21

1 Answers1

2

As noted in the comments, much of what you're attempting is a (very common) inadvisable approach.

If you have multiple data frames with similar names, they should be in a single named list. If you need to refer to columns by strings, don't use $.

Here's a toy example:

dat <- data.frame(x = 1:5,y = letters[1:5])

# A bunch of objects; this is *not* the right way
dat_1_1 <- dat
dat_1_2 <- dat
dat_2_1 <- dat
dat_2_2 <- dat

# One way to recover from that mistake is to grab them all up with ls/mget
ls(pattern = "dat_[0-9]*_[0-9]*")
dat_list <- mget(x = ls(pattern = "dat_[0-9]*_[0-9]*"))

# Then you can select specific data frames from the list, by name use [[
# Note the use of paste0 rather than paste, to avoid spaces in the names 
i <- 1
j <- 2
dat_list[[paste0("dat_",i,"_",j)]]

# And you can assign to them, altering values (avoid assign())
dat_list[[paste0("dat_",i,"_",j)]][2,"x"] <- 500
dat_list[[paste0("dat_",i,"_",j)]]
joran
  • 169,992
  • 32
  • 429
  • 468