Sasanka20 Sasanka20 - 27 days ago 9
R Question

R - creating variable from reading line

I would like to create a variable XO from user's answer on a quick question. And I also would like system to write, what user has selected. The code looks like this:

fun1 <- function() {
XO <- readline(prompt = "Do you want X, or O? ")
if (substr(XO, 1, 1) == "X")
cat("You have chosen X.\n") & XO = "X"
else
cat("You have chosen O.\n") & XO = "O"
}


The function fun1 is created properly, but after answering the question (my answer is e.g. "X"), system shows error:

Error in cat("You have chosen X.\n") & XO = "X" :
target of assignment expands to non-language object


And XO is not created.

Please, could you help me, what am I doing wrong? Thanks in advance.

Answer

In R, & is just used in logical assignments, not for joining sentences. What you wanna do is to put that piece of code in a chunks inside curly brackets {} and split them in different lines. If the condition is true R will run the hole chunk inside the curly brackets.

fun1 <- function() {
  XO <- readline(prompt = "Do you want X, or O? ")
  if (substr(XO, 1, 1) == "X") {
    cat("You have chosen X.\n")
    XO <<- "X"
  } else {
    cat("You have chosen O.\n")
    XO <<- "O"
  }
}

You're using = to assign the XO variable inside the fun1 function. Take a look at this question to be sure that's what you want. If you want it to be available also in the global environment, use <<- instead.

Comments