Reputation: 177
I have the following data frame:
1 2 3 4 5 6
P1 ca100 P4 cb100 P7 cc100
P2 ca075 P5 cb075 P8 cc075
P3 ca050 P6 cb050 P9 cc050
I want to find the names of columns which contains a particular element. For eg, if I want to find the column name containing P1, the output should be 1, the column name for any element with "ca", "cb", "cc" should be 2, 4 and 6 respectively.
Any help will be appreciated. Thanks
Upvotes: 0
Views: 504
Reputation: 7818
You can wrap up str_detect
from stringr
in this way.
colnames_given_pattern <- function(.data, pattern){
suppressWarnings(names(.data)[stringr::str_detect(.data, pattern)])
}
colnames_given_pattern(df, "P1")
#> [1] "1"
colnames_given_pattern(df, "ca")
#> [1] "2"
colnames_given_pattern(df, "ca|cb")
#> [1] "2" "4"
colnames_given_pattern(df, "ca|cb|cc")
#> [1] "2" "4" "6"
Where df
is:
df <- read.table(text="
P1 ca100 P4 cb100 P7 cc100
P2 ca075 P5 cb075 P8 cc075
P3 ca050 P6 cb050 P9 cc050",header=FALSE)
names(df) <- 1:6
df
#> 1 2 3 4 5 6
#> 1 P1 ca100 P4 cb100 P7 cc100
#> 2 P2 ca075 P5 cb075 P8 cc075
#> 3 P3 ca050 P6 cb050 P9 cc050
Upvotes: 1
Reputation: 2141
We can compare each column to the element you are searching for and then return the respective colname:
df <- read.table(text="1 2 3 4 5 6
P1 ca100 P4 cb100 P7 cc100
P2 ca075 P5 cb075 P8 cc075
P3 ca050 P6 cb050 P9 cc050",header=T)
colName.of.Element <- function(df, el)
{
matched.cols <- apply(df, 2, function(col) any(col == el))
return(colnames(df[matched.cols]))
}
colName.of.Element(df,"P1")
[1] "X1"
colName.of.Element(df,"ca100")
[1] "X2"
Upvotes: 0