R: How to Delete All Columns in a Dataframe Except A Specified Few By String [duplicate]

六眼飞鱼酱① 提交于 2019-12-13 12:52:23

问题


I have a data frame in R that consists of around 400 variables (as columns), though I only need 25 of them. While I know how to delete specific columns, because of the impracticality of deleting 375 variables - is there any method in which I could delete all of them, except the specified 25 by using the variable's string name?

Thanks.


回答1:


Sample example:

 df <- data.frame(a=1:5,b=6:10,c=11:15,d=16:20,e=21:25,f=26:30)  # Six columns
 df
    a  b  c  d  e  f
  1 1  6 11 16 21 26
  2 2  7 12 17 22 27
  3 3  8 13 18 23 28
  4 4  9 14 19 24 29
  5 5 10 15 20 25 30

 reqd <- as.vector(c("a","c","d","e")) # Storing the columns I want to extract as a vector
 reqd                                     
 [1] "a" "c" "d" "e"

 Result <- df[,reqd]       # Extracting only four columns
 Result
   a  c  d  e
 1 1 11 16 21
 2 2 12 17 22
 3 3 13 18 23
 4 4 14 19 24
 5 5 15 20 25


来源:https://stackoverflow.com/questions/36565869/r-how-to-delete-all-columns-in-a-dataframe-except-a-specified-few-by-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!