Skip to contents

Find row or column by name or index

Column by name or index: %ci%

Row by name or number: %ri%

Matrix cell index by name or number: %mi%

Return all indices of a (range of) values: %ai%

Is element of... with multiple input types: %e%

Usage

c %ci% d

r %ri% d

rc %mi% d

nv %ai% d

x %e% y

Arguments

c

Column name or index

d

A named vector, list, matrix, or data frame

r

Row name or index

rc

A 2-element numeric or character vector representing c(r,c). Names (character) and indices (numeric) vectors can be mixed if rc is passed as a 2-element list object.

nv

A numeric value, or vector of values of which you want to know the indices in d.

x

A vector, data frame or list containing numbers and/or characters that could be elements of y

y

An object that could contain values in x

Value

If r/c/rc is numeric, the name corresponding to the row/column index of d, if r/c/rc is a character vector, the row/column index corresponding to the row/column name. If dimnames(d) == NULL, but names(d) != NULL then %ci% and %ri% will look up r/c in names(d)

Logical vector indicating which x are an element of y

Author

Fred Hasselman

Examples


# data frame
d <- data.frame(x=1:5,y=6,row.names=paste0("ri",5:1))

"y" %ci% d # y is the 2nd column of d
#> [1] 2
  2 %ci% d # the name of the second column of d is "y"
#> [1] "y"

    2 %ri% d
#> [1] "ri4"
"ri5" %ri% d
#> [1] 1

# change column name
 colnames(d)["y" %ci% d] <- "Yhat"

# mi works on data frames, matrices, tiblles, etc.
 c(5,2) %mi% d
#> [1] "ri1"  "Yhat"
 list(r="ri1",c=2) %mi% d
#> $r
#> [1] 5
#> 
#> $c
#> [1] "Yhat"
#> 

# matrix row and column indices
m <- matrix(1:10,ncol=2, dimnames = list(paste0("ri",0:4),c("xx","yy")))

 1 %ci% m
#> [1] "xx"
 5 %ci% m # no column 5
#> [1] NA

 1 %ri% m
#> [1] "ri0"
 5 %ri% m
#> [1] "ri4"

 c(5,1)%mi%m
#> [1] "ri4" "xx" 
 c(1,5)%mi%m
#> [1] "ri0" NA   

# For list and vector objects ri and ci return the same values
l <- list(a=1:100,b=LETTERS)

  2 %ci% l
#> [1] "b"
"a" %ci% l
#> [1] 1

  2 %ri% l
#> [1] "b"
"a" %ri% l
#> [1] 1

# named vector
v <- c("first" = 1, "2nd" = 1000)

"2nd" %ci% v
#> [1] 2
    1 %ci% v
#> [1] "first"

"2nd" %ri% v
#> [1] 2
    1 %ri% v
#> [1] "first"

# get all indices of the number 1 in v
 1 %ai% v
#>   nv first
#> 1  1     1

# get all indices of the number 3 and 6 in d
 c(3,6) %ai% d
#>   nv row col
#> 1  3   3   1
#> 2  6   1   2
#> 3  6   2   2
#> 4  6   3   2
#> 5  6   4   2
#> 6  6   5   2

# get all indices of values: Z < -1.96 and Z > 1.96
 Z <- rnorm(100)
 Z[Z%)(%c(-1.96,1.96)] %ai% Z
#>                 nv V1
#> 1 2.12685045903409 16
#> 2 2.03936926250284 21
#> 3 2.21176948683873 80
#> 4 1.99311026486264 86
#> 5 2.56440833799741 88