mardi 20 août 2019

R: error handling in finding the row number of a dataframe

I have a dataframe with an ID column and another dummy column. In the first step the user enters a number which should be one of the IDs (ID_edit). Then the respective row index is determined. If the ID is in the dataframe everything works fine. If not (because the user enters a wrong ID or no ID at all) there should be an error message. I tried this:

  test_df <- data.frame("ID" = c(1,3,6,8),
                        "char" = c("a","b","c","d"))

  ID_edit <- as.integer(2)
  row_nr_df <- which(test_df$ID == ID_edit, arr.ind=TRUE)

  View(test_df$ID)
  row_list <- as.numeric(rownames(test_df))

  if(!is.null(row_nr_df %in% row_list)) {
    print("Row number in row list")
  } else {
    print("Row number not in row list")}

  View(row_nr_df)

If I change

  ID_edit <- as.integer(1)

which is working, to

  ID_edit <- as.integer(2)

the if-statement is still TRUE, but I expect and want to have the else block here.

View(row_nr_df)

shows then the message "No data available in table".

In the end I want to access the dataframe with the row number, e.g.:

char_edit <- test_df$char[[row_nr_df]] 

But this is not working, if the row number does not exist .

Aucun commentaire:

Enregistrer un commentaire