首页 > 解决方案 > R - 获取数据框的名称并收集到公式中

问题描述

我在 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

标签: rstringdataframeformula

解决方案


使用as.formulapaste

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)为公式中所需的列名向量即可。


推荐阅读