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!

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 <- list(R1, R2, R3); R_list_dados <- lapply(R_list, "[", c(1,8,11,14,24); R_list_dados2 <- lapply(R_list_dados, function(x) x$E <- c(0,100,200,300,400,500,600)) and so on Commented Dec 5, 2017 at 16:18
  • Do you wan to keep R1, R2... or not? Commented Dec 5, 2017 at 16:18
  • See How do I make a list of data frames for some discussion and examples. Commented Dec 5, 2017 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. Commented Dec 5, 2017 at 18:27

1 Answer 1

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"))
}
Sign up to request clarification or add additional context in comments.

3 Comments

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 <- NULL if you have options(stringsAsFactors=F) and append to df using rbind().
It works, but I need to keep the index to include other values to each one.
By index you mean 1,2,3.. from Data1, Data2, Data3... ? If so parse your file name to get it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.