Picha Pie
Picha Pie

Reputation: 5

How can I extract the coefficient of a specific variable in an equation in R?

For example, I have a string like "2 * a + 3 * b".

I already have something that checks if a certain variable exists in the expression. So for example I input b, how could I make it return the 3?

Upvotes: 0

Views: 120

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269431

1) If we know that the formula is linear, as in the example in the question, then we can take the derivative.

# inputs
s <- "2 * a + 3 * b"
var <- "b"

D(parse(text = s), var)
## [1] 3

2) If in addition there is no constant term -- there is none in the example in the question -- then we can replace all variables with 0 except for the one whose coefficient we want and replace that one with 1. Then evaluate the expression. Assuming the same inputs we have

p <- parse(text = s)
L <- Map(function(x) 0, all.vars(p))   # list(a = 0, b = 0)
eval(p, replace(L, var, 1))
## [1] 3

Upvotes: 3

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

Not sure I understand you 100%. But if it is that you have a string and want to see the digit(s) that occur immediately prior to b, then you can use str_extract:

library(stringr)
str_extract(x, "\\d+(?=b)")
[1] "3"

This works by the look-ahead (?=b), which assterts that the digit(s) to be extracted must be followed by the character b. If you need the extracted substring in numeric format:

as.numeric(str_extract(x, "\\d+(?=b)"))

Data:

x <- "2a+3b"

Upvotes: 1

Related Questions