user12310746
user12310746

Reputation: 279

Returning error message for my function if the argument isn't relevant

I'm practicing writing functions. I wrote a function that splits a column into different columns according to the separator (e.g., ":", "/").

I'm trying to have the function return an error message if the separator isn't relevant.

Here is the part that I am working on:

myfunc <- function(df, colnum = 2, into = c("a", "b", "c"), sep = ":") {

  colnum <- df[ , colnum]

  hold <- strsplit(colnum, split = sep)
  if (!grepl(sep, df)) stop()

}

This is returning an error message even if the separator is relevant. How can I approach this? Thank you.

Upvotes: 1

Views: 25

Answers (1)

akrun
akrun

Reputation: 886938

In the OP's code, the 'colnum' is updated with the column values by assigning colnum <- df[,colnum]. Instead, it can be changed to a different object name. Secondly, the grepl output length would be the same as the number of rows of the dataset and if/else, expects input to be of length 1 and output will be of length 1 as well. In this case, may be, we can wrap with any on the condition to check if there are any sep that are not :

myfunc <- function(df, colnum = 2, into = c("a", "b", "c"), sep = ":") {

    colvec <- df[ , colnum] 

    hold <- strsplit(colvec, split = sep)
    if (any(!grepl(sep, df[, colnum]))) stop()
    hold


   }



myfunc(dat)
#[[1]]
#[1] "1" "2" "3"

#[[2]]
#[1] "1" "2" "3"

#[[3]]
#[1] "1" "2" "3"

#[[4]]
#[1] "1" "2" "3"

#[[5]]
#[1] "1" "2" "3"

myfunc(dat, sep=",")
#Error in myfunc(dat, sep = ",") : 

data

dat <- data.frame(col1 = 1:5, col2 = '1:2:3', stringsAsFactors = FALSE)

Upvotes: 1

Related Questions