I want to set 2 Console output in the if statement: one is the paste() function and sencond is unique values from one of the column
if (x<= 0) {
Paste("Negative"),
unique(data$category)
}
CodePudding user response:
You can't return two things at once, but there are couple of ways to output both objects on the console:
- Assign each object to a variable, and output the variables one at a time
- Store both objects together in a list, and output the list to the console
1. Assign each value to a different variable
The variables will be stored in the global environment, so they will be accessible subsequent to the execution of the if statement.
x <- -3
data <- data.frame(category = c("foo", "bar", "baz"))
if (x <= 0){
my.text <- "Negative"
my.values <- unique(data[["category"]])
}
## Now you can do as you please with these variables. For example:
cat("The value of x is", my.text)
#> The value of x is Negative
length(my.values)
#> [1] 3
Created on 2022-08-23 by the reprex package (v2.0.1)
2. Immediately return a two-element list
x <- -3
data <- data.frame(category = c("foo", "bar", "baz"))
if (x <= 0){
list(
polarity = "Negative",
values = unique(data[["category"]])
)
}
#> $polarity
#> [1] "Negative"
#>
#> $values
#> [1] "foo" "bar" "baz"
Created on 2022-08-23 by the reprex package (v2.0.1)
3. Bonus solution: Use cat()
to print to the console
If you don't actually want to return the objects, but you just want to print them to the console, you can use cat()
. Depending on your aims, you might also consider using message()
, which is designed to give messages to the user (or a log).
x <- -3
data <- data.frame(category = c("foo", "bar", "baz"))
if (x <= 0){
cat("Negative")
cat(data[["category"]])
}
#> Negativefoo bar baz
### or consider:
if (x <= 0){
message("Negative")
message(data[["category"]])
}
#> Negative
#> foobarbaz
Created on 2022-08-23 by the reprex package (v2.0.1)