0

I would like to programm a loop in R to write data frames.

I tried this:

dts <- c('r1', 'r2', 'r3', 'r4', 'r5')
for (dt in dts){
  temp <- data.frame(S=paste0(dt,"_RAW$Zeit"), A=paste0(dt,"_RAW$Wert"))
  assign(dt, temp)
}

But it did not work. The data frame is not correct (there are no values, only these two lines):

  | S           | A
-----------------------------
1 | r1_RAW$Zeit | r1_RAW$Wert

I expect this:

r1 <- data.frame(S=r1_RAW$Zeit, A=r1_RAW$Wert)
r2 <- data.frame(S=r2_RAW$Zeit, A=r2_RAW$Wert)
...
  • Which values are you talking about? – jay.sf Oct 13 '19 at 09:43
  • There are however much better solutions, but try replacing `paste0(dt,"_RAW$Zeit")` with `get(paste0(dt,"_RAW"))$Zeit`. Notice there is a difference between an object name `r1_RAW$Zeit` and the character vector representing it `"r1_RAW$Zeit"`. – sboysel Oct 13 '19 at 09:43
  • Thank you for your time, but unfortunately it doesn't work. I get `Error: $ operator is invalid for atomic vectors`. What would be a better solution? Please give me a hint... –  Oct 13 '19 at 09:57
  • Notice that your question is not [reproducible](https://stackoverflow.com/q/5963269/3277821). For example, what are the `r*_RAW` objects? – sboysel Oct 13 '19 at 10:10
  • These are dataframes, imported from csv files. –  Oct 13 '19 at 10:12
  • They have ten columns, but I only need these two (S=Zeit, A=Wert). –  Oct 13 '19 at 10:13
  • Since there is no reproducible example, the method here might help you [R use paste function as a object in subset function](https://stackoverflow.com/questions/49655013/r-use-paste-function-as-a-object-in-subset-function) – deepseefan Oct 13 '19 at 10:33
  • Thank you @deepseefan! Now it is working, but it leaves out the underscores... What can I do here? –  Oct 13 '19 at 10:46

1 Answers1

0

The trick is to use mget to get all input dataframes at once, outside the for loop. Then, in the loop, extract the columns of interest and assign the new data sets.

dts <- c("r1", "r2", "r3")
r_RAW_list <- mget(paste0(dts, "_RAW"))

for(d in dts){
  i <- grep(d, names(r_RAW_list))
  temp_rRAW <- r_RAW_list[[i]]
  temp <- data.frame(S = temp_rRAW[["Zeit"]], A = temp_rRAW[["Wert"]])
  assign(d, temp)
}
rm(r_RAW_list, temp_rRAW, temp)

ls(pattern = "^r[[:digit:]]$")
#[1] "r1" "r2" "r3"

r1
#            S           A
#1  -1.2070657 -0.47719270
#2   0.2774292 -0.99838644
#3   1.0844412 -0.77625389
#4  -2.3456977  0.06445882
#5   0.4291247  0.95949406
#6   0.5060559 -0.11028549
#7  -0.5747400 -0.51100951
#8  -0.5466319 -0.91119542
#9  -0.5644520 -0.83717168
#10 -0.8900378  2.41583518

Test data creation code.

set.seed(1234)
n <- 10
r1_RAW <- data.frame(Zeit = rnorm(n), Wert = rnorm(n), Other = rnorm(n))
r2_RAW <- data.frame(Zeit = rnorm(n), Wert = rnorm(n), Other = rnorm(n))
r3_RAW <- data.frame(Zeit = rnorm(n), Wert = rnorm(n), Other = rnorm(n))
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66