游.程 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 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路