游.程 2011-03-08 14:56 采纳率: 0%
浏览 349
已采纳

如何在数据框架中按名称删除列

I have a large data set and I would like to read specific columns or drop all the others.

data <- read.dta("file.dta")

I select the columns that I'm not interested in:

var.out <- names(data)[!names(data) %in% c("iden", "name", "x_serv", "m_serv")]

and than I'd like to do something like:

for(i in 1:length(var.out)) {
   paste("data$", var.out[i], sep="") <- NULL
}

to drop all the unwanted columns. Is this the optimal solution?

转载于:https://stackoverflow.com/questions/5234117/how-to-drop-columns-by-name-in-a-data-frame

  • 写回答

10条回答 默认 最新

  • local-host 2011-03-08 15:03
    关注

    You should use either indexing or the subset function. For example :

    R> df <- data.frame(x=1:5, y=2:6, z=3:7, u=4:8)
    R> df
      x y z u
    1 1 2 3 4
    2 2 3 4 5
    3 3 4 5 6
    4 4 5 6 7
    5 5 6 7 8
    

    Then you can use the which function and the - operator in column indexation :

    R> df[ , -which(names(df) %in% c("z","u"))]
      x y
    1 1 2
    2 2 3
    3 3 4
    4 4 5
    5 5 6
    

    Or, much simpler, use the select argument of the subset function : you can then use the - operator directly on a vector of column names, and you can even omit the quotes around the names !

    R> subset(df, select=-c(z,u))
      x y
    1 1 2
    2 2 3
    3 3 4
    4 4 5
    5 5 6
    

    Note that you can also select the columns you want instead of dropping the others :

    R> df[ , c("x","y")]
      x y
    1 1 2
    2 2 3
    3 3 4
    4 4 5
    5 5 6
    
    R> subset(df, select=c(x,y))
      x y
    1 1 2
    2 2 3
    3 3 4
    4 4 5
    5 5 6
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?