1

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.

Jaroslav Bezděk
  • 6,967
  • 6
  • 29
  • 46

1 Answers1

1

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.

Community
  • 1
  • 1
Tomás Barcellos
  • 814
  • 16
  • 26
  • Thank you for help. However, when I run the code you wrote, the system tells me, that object "XO" is not found. Do you know, how to solve this problem? – Jaroslav Bezděk Nov 06 '16 at 14:21