Search code examples
rinteractive

printing a tibble or data frame in an interactive user input with select.list


I want to capture some user input in the R console. Along with capturing the user input I want to print a tibble that helps the user decide which input to select. Here's a simple example:

library(tidyverse)
input <- tibble(color = c("blue", "green"),
                words = c("test", "hello"))
                
utils::select.list(c(as.character(c("Yes", "No"))),
                     title = print(c(input, "\nDo all words contain letters?")),
                     multiple = FALSE)

This obviously doesn't work since select.list says:

'title' must be NULL or a length-1 character vector

So question is how I could print the tibble along with the question/message and capture teh user input. Happy to use sth. else than select.input.

The ideal print would be sth. like:

# A tibble: 2 x 2
  color words
  <chr> <chr>
1 blue  test 
2 green hello

Do all words contain letters?

1: Yes
2: No

Solution

  • You could wrap in a function, as below:

    f <- function(tbl) {
      print(tbl)
      cat("\n")
      utils::select.list(
        c(as.character(c("Yes", "No"))),
        title = "Do all words contain letters?",
        multiple = FALSE)
    }
    

    Usage

    f(input)
    
    # A tibble: 2 x 2
      color words
      <chr> <chr>
    1 blue  test 
    2 green hello
    
    Do all words contain letters? 
    
    1: Yes
    2: No