dimanche 23 octobre 2016

Subset Columns based on partial matching of column names in the same data frame

I would like to understand how to subset multiple columns from same data frame by matching the first 5 letters of the column names with each other and if they are equal then subset it and store it in a new variable.

Here is a small explanation of my required output. It is described below,

Lets say the data frame is eatable

fruits_area   fruits_production  vegetable_area   vegetable_production 

12             100                26               324
33             250                40               580
66             510                43               581

eatable <- data.frame(c(12,33,660),c(100,250,510),c(26,40,43),c(324,580,581))
names(eatable) <- c("fruits_area", "fruits_production", "vegetables_area",
          "vegetable_production")

I was trying to write a function which will match the strings in a loop and will store the subset columns after matching first 5 letters from the column names.

checkExpression <- function(dataset,str){
    obje[grepl((str),names(dataset),ignore.case = TRUE)]
}

checkExpression(d,"your_string")

The above function checks the string correctly but I am confused how to do matching among the column names in the dataset.

Note:- I am a beginner in R. Please help me regarding the issue. Thank you.

Aucun commentaire:

Enregistrer un commentaire