Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

dataframe - How to remove certain columns in multiple data frames in R?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

data

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...