AndrewMacDonald AndrewMacDonald - 21 days ago 5
R Question

Extracting a variable from a formula

Is there a way to extract the response variable from a formula, even if that formula contains a function?

x1 <- ~responsename

as.character(x1[[2]])

x2 <- ~log(responsename)

as.character(x2[[2]][[2]])


Both of these approaches give the desired answer (
"responsename"
). But is there a way to get the same answer in either case, automatically?

ps: assuming that the formula is always
~ responsename
or
~ f(responsename)
, no
+
etc.

Answer
tail(all.names(x1),1)

seems to do what you want. e.g.

tail(all.names(x2),1)
#[1] "responsename"
tail(all.names(x1),1)
#[1] "responsename"
tail(all.names(~sin(responsename)),1)
#[1] "responsename"
tail(all.names(~(responsename)^2),1)
#[1] "responsename"