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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.