0

I need to return number of element in vector based on vector element name. Lets say i have vector of letters:

myLetters=letters[1:26]
> myLetters
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"

and what I intent to do is to create/find function that returns me the number of element when called for example:

myFunction(myLetters["b"])
[1] 2

myFunction(myLetters["z"])
[1]26

In summary I need a way to refer to excel columns by writing letters of a column (A,B,C later maybe even AA or further) and to get the number.

Jaap
  • 81,064
  • 34
  • 182
  • 193
Alexandros
  • 331
  • 1
  • 14

2 Answers2

1

If you want to refer to excel columnnames, you could create a reference vector with all possible excel column names:

eg1 <- expand.grid(LETTERS, LETTERS)
eg2 <- expand.grid(LETTERS, LETTERS, LETTERS)
excelcols <- c(LETTERS, paste0(eg1[[2]], eg1[[1]]), paste0(paste0(eg2[[3]], eg2[[2]], eg2[[1]])))

After which you can use which:

> which(excelcols == 'A')
[1] 1
> which(excelcols == 'AB')
[1] 28
> which(excelcols == 'ABC')
[1] 731
Jaap
  • 81,064
  • 34
  • 182
  • 193
0

If you need to find the number of times specific letter occurs then the following should work:

myLetters = c("a","a", "b")

myFunction = function(myLetters, findLetter){
  length(which(myLetters==findLetter))
}

Let find how many times "a" occurs in myLetters:

myFunction(myLetters, "a")
# [1] 2
Aleksandr
  • 1,814
  • 11
  • 19