Add columns within a for loop R
r
Solution
Something like this?? :
fileNames <- list.files()
master1 <- read.csv(file = fileNames[1], sep = ";", header = T)
for(i in 2:length(fileNames)){
file1 <- read.csv(file = fileNames[i], sep = ";", header = T)
master1$newCol1 <- file1[,2]
colnames(master1)[ncol(master1)] <- paste("file",i,sep = "")
}
Problem
This is a part of a larger script- long story short, input to R is a semi-colon separated path to the location of my text files. All the text files are of the following format: File1: ``` Name1 3 Name2 4 Name3 55 ``` File2: ``` Name1 4 Name2 33 Name3 102 ``` File3: ``` Name1 12 Name2 2 Name5 33 ``` Here is an example: ``` cond1<-'/User/Desktop/File1;/User/Desktop/File2;/User/Desktop/File3' #separates the elements normalList<-strsplit(cond1, ";") #now you can access each element nor<-unlist(normalList) baseNorm<-vector("list", length(nor)) dirNorm<-vector("list", length(nor)) pathNorm<-vector("list", length(nor)) Norm<-vector("list", length(nor)) new<-vector("list", length(nor)) for (i in 1:length(nor)) { baseNorm[[i]] <- basename(nor[i]) dirNorm[[i]]<-dirname(nor[i]) pathNorm[[i]]<-paste(dirNorm[[i]], baseNorm[[i]], sep="/") Norm[[i]]<-read.delim(pathNorm[[i]], header=F) } ``` In the example here the input to R contains 3 files- however I need the script to be flexible enough that it can work for any number of files passed, hence the attempt with the for loop. The BIG IDEA is: 1) Get the path to the specific file for all files. 2) Load the text files into R 3) Create a new file that contains the common first column (Name1, Name2, Name3). All the next columns in this new file correspond to the 2nd column of File1, File2, File3, File4, etc. Essentially, I need to create a master file: ``` Name1 3 4 55 Name2 4 33 102 Name3 12 2 33 ``` I am sure there is a much simpler solution even to the code I already have, since with all the [[]] I don't even know how to start writing a function that creates the master file. I just started using R, so any input is a valuable learning experience, and thank you in advance!