R Program to extract specific column from a data frame using column name


November 12, 2021, Learn eTutorial
743

How to extract specific column from a data frame using column name

Here we are explaining how to write an R program to extract a specific column from a data frame using a column name. Here we are using a built-in function data.frame() 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. The syntax of this function is 



data.frame(…, row.names = NULL, check.rows = FALSE,check.names = TRUE, fix.empty.names = TRUE,stringsAsFactors = default.stringsAsFactors()) 

Where dots(...) indicates the arguments are of either the form value or tag = value and row. name is a NULL or a single integer or character string.

How to extract a specific column from a data frame using column name in the R program

Below are the steps used in the R program to extract specific columns from a data frame using a column name. 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.

ALGORITHM

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

STEP 2: First print original vector values

STEP 3: Call the function data.frame for extracting specific column as data.frame(E$N,E$S)

STEP 4: Assign variable result with the result of data.frame function

STEP 5: print the variable result which holding the result 

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)
print("Extract Specific columns:")
result <- data.frame(E$N,E$S)
print(result)
                                      

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

[1] "Extract Specific columns:"
         E.N            E.S
1       Jhon            10
2       Hialy           9.5
3       Albert          12.2
4       James           11
5       Delma           8