ℙℕℤℝ 2011-01-05 14:34
浏览 372
已采纳

按名称删除数据帧列

I have a number of columns that I would like to remove from a data frame. I know that we can delete them individually using something like:

df$x <- NULL

But I was hoping to do this with fewer commands.

Also, I know that I could drop columns using integer indexing like this:

df <- df[ -c(1, 3:6, 12) ]

But I am concerned that the relative position of my variables may change.

Given how powerful R is, I figured there might be a better way than dropping each column one by one.

转载于:https://stackoverflow.com/questions/4605206/drop-data-frame-columns-by-name

  • 写回答

19条回答 默认 最新

  • 游.程 2011-01-05 14:40
    关注

    You can use a simple list of names :

    DF <- data.frame(
      x=1:10,
      y=10:1,
      z=rep(5,10),
      a=11:20
    )
    drops <- c("x","z")
    DF[ , !(names(DF) %in% drops)]
    

    Or, alternatively, you can make a list of those to keep and refer to them by name :

    keeps <- c("y", "a")
    DF[keeps]
    

    EDIT : For those still not acquainted with the drop argument of the indexing function, if you want to keep one column as a data frame, you do:

    keeps <- "y"
    DF[ , keeps, drop = FALSE]
    

    drop=TRUE (or not mentioning it) will drop unnecessary dimensions, and hence return a vector with the values of column y.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(18条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题