1

I'm a new programmer and I'm stuck with the creation of a function or loop to avoid repetition of the lines.

Here is part of my code:

# Importing dataframes
R1 <- read.table("C:/Users/Data1.txt", header = TRUE)
R2 <- read.table("C:/Users/Data2.txt", header = TRUE)
R3 <- read.table("C:/Users/Data3.txt", header = TRUE)

# Taking only the colunms that I need from each dataframe
R1_dados <- R1[,c(1,8,11,14,24)]
R2_dados <- R2[,c(1,8,11,14,24)]
R3_dados <- R3[,c(1,8,11,14,24)]

# Adding some colunms 
R1_dados$E <- c(0,100,200,300,400,500,600)
R2_dados$E <- c(0,100,200,300,400,500,600)
R3_dados$E <- c(0,100,200,300,400,500,600)

# Doing some math between columns from each dataframe
R1_dados$rETR = R1_dados$fvfm*R1_dados$E
R2_dados$rETR = R2_dados$fvfm*R2_dados$E
R3_dados$rETR = R3_dados$fvfm*R3_dados$E

# and so on...

I was wondering if I can create an index of the replicas (R1, R2, and R3)

I'll be grateful if someone helps me. Thanks!

CS3420
  • 11
  • 1
  • 4
  • If the operations are so similar you could store `R1 - R3` in a list and then each operation becomes a simple `lapply`. Something like: `R_list – Mike H. Dec 05 '17 at 16:18
  • Do you wan to keep R1, R2... or not? – Emmanuel-Lin Dec 05 '17 at 16:18
  • See [How do I make a list of data frames](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207) for some discussion and examples. – Gregor Thomas Dec 05 '17 at 16:36
  • Yes, I do need to keep R1, R2... In addition, later in the code, I need to create a column with different values to each one. – CS3420 Dec 05 '17 at 18:27

1 Answers1

1

You should loop on a file list.

fileList <- c("Data1", "Data2", "Data3")
for (file in fileList){
  R <- read.table(paste0("C:/Users/", file, ".csv"))
  R_dados <- R[,c(1,8,11,14,24)]
  R_dados$E <- c(0,100,200,300,400,500,600)
  R_dados$rETR = R_dados$fvfm*R3_dados$E
  write.table(R_dados, file = paste0("C:/Users/", file, "_dados.csv"))
}
Emmanuel-Lin
  • 1,465
  • 1
  • 10
  • 25
  • I agree with @Emmanuel-Lin. Also, if you don't want to create a new output file but just want to import them into a single datafram, you can initialize the dataframe with `df – Nate Dec 05 '17 at 16:24
  • It works, but I need to keep the index to include other values to each one. – CS3420 Dec 05 '17 at 18:29
  • By index you mean 1,2,3.. from Data1, Data2, Data3... ? If so parse your file name to get it – Emmanuel-Lin Dec 06 '17 at 08:21