Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 583
Biotechgeek Avatar asked Jul 11 '19 12:07

Biotechgeek


People also ask

How to solve linear algebraic equation in R?

solve () function in R Language is used to solve linear algebraic equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated. Syntax: solve (a, b) Parameters: a: coefficients of the equation. b: vector or matrix of the equation.

How to solve an equation for a specified variable?

Solving an Equation for a Specified Variable. Examples: 1. Solve for Solve for b 1. A = 1/2h (b 1 + b 2) 2. Solve for z. 3z + x - y = 2x + 4. Show Step-by-step Solutions.

How to solve an equation using two matrices in R?

solve () function in R Language is used to solve the equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated. To solve this using two matrices in R we use the following code:

What is the solve function in R?

In other words, the solve function is computing the inverse of a matrix, if no right-hand side matrix is specified. Let’s do this in practice: First, we have to create another example matrix in R:


1 Answers

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
like image 134
Stéphane Laurent Avatar answered Sep 16 '22 16:09

Stéphane Laurent