简体   繁体   English

如何将分数表达式转换为 R 中的字符向量?

[英]How can I convert a fraction expression into a character vector in R?

Hello an thanks for the help.您好,感谢您的帮助。

I want to convert the expression: x / y (eg 1298 / 1109) into a character vector: "x / y" (eg "1298 / 1109") using R.我想使用 R 将表达式:x / y(例如 1298 / 1109)转换为字符向量:“x / y”(例如“1298 / 1109”)。

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.我已经尝试使用 as.character(x/y) 和 as.character.Date(x/y) 但这只会将分数的结果转换为字符向量。

Do you mean this?你是这个意思吗?

> deparse(quote(1298 / 1109))
[1] "1298/1109"

or或者

> f <- function(x) deparse(substitute(x))

> f(1298 / 1109)
[1] "1298/1109"

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.使用paste的替代解决方案,正如 Allan 在评论中提到的,包装在 function 中。不如 Tomas 的解决方案灵活,但简单。

f <- function(x,y) {
  paste(x, y, sep = " / ")
}

f(1298, 1109)

[1] "1298 / 1109"

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或者不让它成为一个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"

With MASS , there is fractions function对于MASS ,有fractions function

 MASS::fractions(1298/1109)
[1] 1298/1109

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM