如何删除R中多个数据框中的某些列? [英] How to remove certain columns in multiple data frames in R?

查看:963
本文介绍了如何删除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.

推荐答案

假设您有几个data.frames dat1 dat2 dat3 等。单个数据集,将它们放在列表中并进行处理。删除第一列后,如果仍然需要原始的 data.frame 对象来反映更改(不建议这样做,因为您可以在列表本身中进行所有分析),使用 list2env

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

如果您有不同的数据集名称 D1 C1 datC newDat 等没有明确的常用模式(问题中不清楚),那么您仍然可以手动创建列表(极端情况)

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)

并执行 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))

这篇关于如何删除R中多个数据框中的某些列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆