Reputation: 302
lets say I have many data frames with different names of almost similar columns. How do I manipulate the columns of individual data frames using loops (or any other way)? For example, I want to remove the first column of all data frames at once.
Upvotes: 1
Views: 4022
Reputation: 887028
Suppose you have several data.frames dat1
, dat2
, dat3
, etc. Instead of working with individual datasets, place them in a list
and do the processing. After the removal of first column, if you still need the original data.frame
object to reflect the change (not advised as you can do all the analysis within the list itself), use list2env
.
lst <- mget(ls(pattern='^dat\\d+'))
list2env(lapply(lst,`[`,-1), envir=.GlobalEnv)
dat1
If you have different dataset names D1
, C1
, datC
, newDat
etc with no clear common patterns (not clear from the question), then you could still create a list manually (extreme cases)
lst1 <- list(D1=D1, C1=C1, datc=datC, newDat=newDat)
and do the list2env(lapply(...
Or read all the files (if all the files are in the working directory) directly into a list and process it.
files <- list.files() #if you want to read all the files in working directory
lst2 <- lapply(files, function(x) read.table(x, header=TRUE))
lapply(lst2,`[`,-1)
set.seed(24)
dat1 <- as.data.frame(matrix(sample(1:40, 5*3, replace=TRUE), ncol=5))
dat2 <- as.data.frame(matrix(sample(20, 3*5, replace=TRUE), ncol=3))
dat3 <- as.data.frame(matrix(sample(80, 2*10, replace=TRUE), ncol=2))
Upvotes: 7