R Program to drop column(s) by name from a given data frame

How to drop column(s) by name from a given data frame

Here we are explaining how to write an R program to drop column(s) by name from a given data frame. Here we are using a built-in function data.frame(),subset() for this. A data frame is used for storing data tables which has a list of vectors with equal length. The data frames are created by function data.frame(), which has tightly coupled collections of variables. And the function subset() is helping to return subsets of vectors, matrices, or data frames that meet conditions. The syntax of this function is, 


subset(x, …) 

Where dots(...) indicates arguments to be passed to or from other methods and x is the object to be subsetted.

How to drop column(s) by name from a given data frame in the R program

Below are the steps used in the R program to drop column(s) by name from a given data frame. In this R program, we directly give the data frame to a built-in function. Here we are using variables E, N, S, A, Q for holding different types of vectors. Call the function data.frame() for creating dataframe. Finally, drop column by name from a given data frame by calling like subset(E, select = -c(N, Q))

ALGORITHM

STEP 1: Assign variables E,N,S,A,Q with vector values 

STEP 2: First print original vector values

STEP 3: Drop the specified columns by creating a subset of data frame as subset(E, select = -c(N, Q))

STEP 4: Print the final data frame

R Source Code

                                          E = data.frame(
N = c('Jhon', 'Hialy', 'Albert', 'James', 'Delma'),
S = c(10, 9.5, 12.2, 11, 8),
A = c(2, 1, 2, 4, 1),
Q = c('yes', 'no', 'yes', 'no', 'no')
)
print("Original dataframe:")
print(E)
E= subset(E, select = -c(N, Q))
print(E)
                                      

OUTPUT

[1] "Original dataframe:"
     name    score attempts qualify
1  Jhon       10        2     yes
2  Hialy      9.5       1     no
3  Albert     12.2      2     yes
4  James      11        4     no
5  Delma      8         1     no

 S A
1 10.0 2
2  9.5 1
3 12.2 2
4 11.0 4
5  8.0 1