How to subset row values based on columns name in R data frame?

R ProgrammingServer Side ProgrammingProgramming

To subset row values based on columns name in R data frame, we can follow the below steps −

  • First of all, create a data frame.
  • Then, create a sample of column names of size equal to number of rows in the data frame and row names in the same manner with seq_len function, after that use cbind function to subset the rows based on columns name.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

Gender_1<-sample(c("Male","Female"),20,replace=TRUE)
Gender_2<-sample(c("Male","Female","Unknown"),20,replace=TRUE)
df<-data.frame(Gender_1,Gender_2)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

  Gender_1 Gender_2
1 Female Female
2 Female Female
3 Male Male
4 Male Male
5 Male Male
6 Male Female
7 Female Male
8 Female Female
9 Male Male
10 Female Male
11 Male Female
12 Female Male
13 Male Female
14 Female Female
15 Female Male
16 Female Female
17 Female Female
18 Female Female
19 Male Unknown
20 Female Female

Subset the rows based on columns name

Using sample function to create a sample column names and row names in the same manner with seq_len function, after that using cbind function to subset the rows based on columns name created with sample function −

 Live Demo

Gender_1<-sample(c("Male","Female"),20,replace=TRUE)
Gender_2<-sample(c("Male","Female","Unknown"),20,replace=TRUE)
df<-data.frame(Gender_1,Gender_2)
Columns<-sample(c("Gender_1","Gender_2"),20,replace=TRUE)
rownames(df)<-seq_len(nrow(df))
df[cbind(rownames(df),Columns)]

Output

[1] "Female" "Female" "Male" "Male" "Male" "Female" "Female" "Female"
[9] "Male" "Female" "Female" "Female" "Male" "Female" "Female" "Female"
[17] "Female" "Female" "Male" "Female"
raja
Published on 04-Aug-2021 12:44:03
Advertisements