问题
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