0

How to specify the input to be only numeric class in a function in R?. For example,

read_data <- function(file_name, sheet, sample_list = stop("'sample_list' must be provided")){
    ibrary(readxl)
    data = read_excel(file_name, sheet = 2)
    meantritc = sapply(samplelist, function(x)data[grep(x, pattern = data$Source),]$Mean)
    names(data) = sample_list
    return(data)
    }

How do if sheetname is mentioned instead as read.xlsx() requires, it should be able to print a message to provide sheet number intread?

PDM
  • 84
  • 10
  • Please provide more clarification. `read.xlsx()` is not mentioned anywhere in your function, and it looks like you are setting default of `sheet = 2` in the `read_excel()` function you're using. Not clear what you're asking exactly. – 93i7hdjb Mar 07 '18 at 18:00
  • 1
    I hope my edit makes it clearer. – PDM Mar 07 '18 at 18:16
  • If you want dynamic user input, you can use `readline`, but it's unusual to have a user update an input mid-function - I'd recommend Erik's approach of just throwing a useful error message so the user can correct the input and call the function fresh. – Gregor Thomas Mar 07 '18 at 19:16

1 Answers1

1

You can accomplish this by placing the following within your fucntion:

if (is.character(sheet))
{
   stop("Sheet must be a number!")
}
93i7hdjb
  • 1,136
  • 1
  • 9
  • 15
  • Thanks. Thats sensible. Could you suggest how in this case I can use tryCatch()? – PDM Mar 07 '18 at 18:24
  • 1
    well, tryCatch is really meant for things like doing X if Y fails. In this case, it seems like if sheet is a not a number, there's no other alternative for your user but to try and enter an appropriate value. As such I wouldn't recommend it in this case. Nevertheless, here's a great SO post on the `tryCatch()` function: https://stackoverflow.com/questions/12193779/how-to-write-trycatch-in-r – 93i7hdjb Mar 07 '18 at 18:33
  • `tryCatch` seems inappropriate here - if you have a backup plan in case something is not a number, maybe use `warning()` instead of `stop` and proceed with your backup plan. – Gregor Thomas Mar 07 '18 at 19:12
  • Thanks @ErikKornet and Gregor for clarifying – PDM Mar 07 '18 at 20:11