【问题标题】:R: How to remove columns from a dataframe dynamicallyR:如何从数据框中动态删除列
【发布时间】:2015-07-22 09:13:26
【问题描述】:

我有一个包含 2200 行的数据集。我必须一次删除大量列(例如:大约 400 列)。此操作非常频繁地发生,并且要删除的列每次都不同。要删除的列将位于文本文件中。

这就是我解决这个问题的方法。

#Reading data
myData = read.csv("myDataFile.csv")

#Getting the column names which should be deleted
colToDelete = read.table("columnsToBeRemoved.txt")

#processing the names list
tempList = as.character(unlist(colToDelete))
cat(paste(shQuote(tempList, type="cmd"), collapse=","))

newDataSet = subset(myData, select = - ??)

我使用cat(paste(shQuote(tempList, type="cmd"), collapse=",")) 来获取逗号分隔字符串中的名称列表。这个的输出是

“04_ic_1306”,“13_iecdh1_1363”,“18_iechs_1320”,“26_iecsms35_1347”,“33_iecs_1301”,“34_iecumn_1333”,“36_ieko11_1354”,“39_ijo1366”,“47_iz_1308”,“54_ISFXV_1172”。

我尝试了子集和 data.table 方法,但我没有使用这两种方法。我收到以下错误。我无法为 select 命令指定字符串。

-a 中的错误:一元运算符的参数无效

我主要指的是这个previous stackoverflow question

【问题讨论】:

  • 因为你没有给出一个可重复的例子,我不得不猜测,但subset(d, select=setdiff(names(d), tempList) 可能会起作用。有关可重现的示例,请参阅stackoverflow.com/questions/5963269/…
  • 嗨,Kasterma,抱歉之前的评论。你的方法工作得很好。谢谢你的回答。

标签: r dynamic dataframe multiple-columns


【解决方案1】:
b<- "04_ic_1306"
a[,paste(b)]<-NULL

现在要迭代地执行此操作,您可能必须编写一个循环并将文件名保存在这样的数组中

[1] "04_ic_1306"       "06_iEC042_1314"   "13_iEcDH1_1363"   "18_iEcHS_1320"   
[5] "26_iEcolC_1368"   "31_iEcSMS35_1347" "33_iECs_1301"     "34_iECUMN_1333"  
[9] "36_iEKO11_1354"   "39_iJO1366"       "47_iZ_1308"       "54_iSFxv_1172" 

【讨论】:

  • 谢谢 Ann283。你的方法也有效。但我想卡斯特玛的答案应该是可以接受的答案。
【解决方案2】:

这可能是您的解决方案:

# Create data frame with 5 columns
df <- data.frame(a=rnorm(10), b=rnorm(10), c=rnorm(10), d=rnorm(10), e=rnorm(10))

# Select two columns to be removed
remove_col <- c("b", "d")

# Identify them in the column names
remove_col <- names(df) %in% remove_col

# Remove them using an inverse (the !) logical vector
df[,!remove_col]

【讨论】:

    猜你喜欢
    • 2022-09-22
    • 2021-01-07
    • 2020-06-30
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多