Rspacer
Rspacer

Reputation: 2429

How to solve an equation for a given variable in R?

This is equation a <- x * t - 2 * x. I want to solve this equation for t. So basically, set a = 0 and solve for t . I am new to the R packages for solving equations. I need the package that solves for complex roots. The original equations I am work with have real and imaginary roots. I am looking for an algebraic solution only, not numerical.

I tried:

a <- x * t - 2 * x
solve(a,t)

I run into an error:

Error in solve.default(a, t) : 'a' (1000 x 1) must be square

Upvotes: 6

Views: 17472

Answers (2)

RBeginner
RBeginner

Reputation: 254

You might be looking for optimize:

a=function(x,t) x*t-2*x
optimize(a,lower=-100,upper=100,t=10)
optimize(a,lower=-100,upper=100,x=2)

Upvotes: 2

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

You can use Ryacas to get the solution as an expression of x:

library(Ryacas)

x <- Sym("x")
t <- Sym("t")

Solve(x*t-2*x == 0, t)
# Yacas vector:
# [1] t == 2 * x/x

As you can see, the solution is t=2 (assuming x is not zero).

Let's try a less trivial example:

Solve(x*t-2*x == 1, t)
# Yacas vector:
# [1] t == (2 * x + 1)/x

If you want to get a function which provides the solution as a function of x, you can do:

solution <- Solve(x*t-2*x == 1, t)
f <- function(x){}
body(f) <- yacas(paste0("t Where ", solution))$text
f
# function (x) 
# (2 * x + 1)/x

Upvotes: 7

Related Questions