R - 获取数据框的名称并收集到公式中
R - Take colnames of dataframe and collect into a formula
我在 R 中有以下数据集类型:
col1 col2 col3 col4 col5 col6 col7
1 h s h s s l
2 l m s l h s
3 m h l l h l
4 vh s h l s s
5 vl s s vl s l
6 m s l h l h
7 l s l h h h
8 l s h m s h
其中 colX
是数据框的通用列名。
我想创建一个函数,作为输入 - 比方说 -
四个所需的 colX
(例如,col1
、col3
、col4
、col7
)
可以转换如下:
col1 + col3 + col4 + col7
使用as.formula
和paste
:
f <- function(x) as.formula(paste("dependent_variable ~",
paste(colnames(x), collapse="+")))
dat <- data.frame(col1=rnorm(10),
col2=rnorm(10),
col3=rnorm(10))
f(dat)
#> dependent_variable ~ col1 + col2 + col3
显然,您只需将 colnames(x)
更改为公式中所需的列名向量。
我在 R 中有以下数据集类型:
col1 col2 col3 col4 col5 col6 col7
1 h s h s s l
2 l m s l h s
3 m h l l h l
4 vh s h l s s
5 vl s s vl s l
6 m s l h l h
7 l s l h h h
8 l s h m s h
其中 colX
是数据框的通用列名。
我想创建一个函数,作为输入 - 比方说 -
四个所需的 colX
(例如,col1
、col3
、col4
、col7
)
可以转换如下:
col1 + col3 + col4 + col7
使用as.formula
和paste
:
f <- function(x) as.formula(paste("dependent_variable ~",
paste(colnames(x), collapse="+")))
dat <- data.frame(col1=rnorm(10),
col2=rnorm(10),
col3=rnorm(10))
f(dat)
#> dependent_variable ~ col1 + col2 + col3
显然,您只需将 colnames(x)
更改为公式中所需的列名向量。