[英]extracting unique elements of a string vector
I have a string vector shown below as Current output
.我有一个字符串向量,如下所示
Current output
。 I wonder if there a way to extract the unique elements of this vector (exclude "(Intercept)"
) to achieve my Desired output
below?我想知道是否有办法提取此向量的唯一元素(不包括
"(Intercept)"
)以实现下面我Desired output
?
Reproducible code:可重现的代码:
dat <- transform(mtcars, vs=ifelse(vs==0,"y","n"))
m <- lm(mpg ~ cyl + hp + wt*vs+factor(gear), data = dat)
names(m$coef)
# Current output:
[1] "(Intercept)" "cyl" "hp" "wt"
[5] "vsy" "factor(gear)4" "factor(gear)5" "wt:vsy"
# Desired output:
[1] "cyl" "hp" "wt" "vs"
[5] "gear" "wt:vs"
We may get the term.labels
attributes and extract the substring within the ()
if present我们可以获得
term.labels
属性并在()
中提取 substring(如果存在)
sub("[^:]+\\(([^)]+).*", "\\1", attr(terms(m), "term.labels"))
-output -输出
[1] "cyl" "hp" "wt" "vs" "gear" "wt:vs"
For the updated model对于更新 model
m2 <- lm(mpg ~ cyl + hp + wt*vs*factor(gear)+0, data = dat)
sub("[^:]+\\(([^)]+).*", "\\1", attr(terms(m2), "term.labels"))
[1] "cyl" "hp" "wt" "vs" "gear"
[6] "wt:vs" "wt:gear" "vs:gear" "wt:vs:gear"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.