0

I am writing a function where I want to make sure that the input is a vector. As tibbles do not automatically drop to vectors when a singe column is returned, I want to make sure within the function that I am working with a vector. I tried the following both with as.name and as.symbol and failed.

vectorSupposedly <- tibble(ids=c("v1231","v32141","v64364"))

MyFunction <- function(charVector) {
   if (!is.character(charVector)) {
     # Extracting the name of the supposedly 1 column and turning it to a name instead of character
     colName <- as.name(names(charVector)[1])
     charVector<- `$`(charVector, colName)
   }
   class(charVector)
}

# And here is what I get
> MyFunction(vectorSupposedly)
[1] "NULL"
Warning message:
Unknown or uninitialised column: 'colName'.

What am I doing wrong?

Frank
  • 66,179
  • 8
  • 96
  • 180
deann
  • 756
  • 9
  • 24
  • Maybe you could clarify the output you expect. If you want a char vector, why not `if (is.character(x)) do_stuff else stop("gimme chars")` ? – Frank Feb 26 '18 at 18:42
  • 3
    `$` is meant for interactive use, `charVector <- `[[`(charVector, colName)` solves the problem. I really don't know the reason why your attempt fails, I only know that when programming I always use `[[`. – Rui Barradas Feb 26 '18 at 18:49
  • @RuiBarradas Yep, that works fine. I was just curious what is wrong with the above approach. – deann Feb 26 '18 at 18:57
  • @Frank Same reason .. curiosity :) – deann Feb 26 '18 at 18:59
  • Fair enough :) For more along the same lines, here's my older question: https://stackoverflow.com/questions/18216084/lapply-ing-with-the-function – Frank Feb 26 '18 at 19:02
  • 2
    In the documentation for `[[` and `$` it says "Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does." In your function, for example, `colName` is computed. – ngm Feb 26 '18 at 19:05

0 Answers0