Hello an thanks for the help.
I want to convert the expression: x / y (e.g. 1298 / 1109) into a character vector: "x / y" (e.g. "1298 / 1109") using R.
I have tried it with as.character(x/y) and with as.character.Date(x/y) but this only turns the result of the fraction into a character vector.
CodePudding user response:
Do you mean this?
> deparse(quote(1298 / 1109))
[1] "1298/1109"
or
> f <- function(x) deparse(substitute(x))
> f(1298 / 1109)
[1] "1298/1109"
CodePudding user response:
An alternative solution using paste
, as mentioned by Allan in the comments, wrapped in a function. Not as flexible as the solution by Tomas, but simple.
f <- function(x,y) {
paste(x, y, sep = " / ")
}
f(1298, 1109)
[1] "1298 / 1109"
CodePudding user response:
As an addition to the excellent answers already given, in case that one wants to be able to evaluate the expression at some point you can take this approach.
x <- 1298
y <- 1109
z <- as.expression(substitute(x / y, list(x = x, y = y)))
z
# expression(1298/1109)
class(z)
# [1] "expression"
eval(z)
# [1] 1.1704
as.character(z)
# [1] "1298/1109"
Or without making it an expression
t <- substitute(x / y, list(x = x, y = y))
t
# 1298/1109 # not a string, but a "call"
class(t)
# [1] "call"
eval(t)
# [1] 1.1704
deparse(t)
# [1] "1298/1109"
CodePudding user response:
With MASS
, there is fractions
function
MASS::fractions(1298/1109)
[1] 1298/1109