斗士狗 2011-03-08 14:56 采纳率: 0%
浏览 423
已采纳

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

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条回答 默认 最新

  • 狐狸.fox 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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试