r - 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
解决方案
使用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)
为公式中所需的列名向量即可。
推荐阅读
- javascript - 根据 php 脚本中的作业订单安排 cron 作业的更好方法
- cytoscape.js - 如果添加子节点,Dagre 中的布局不显示层次结构
- reactjs - 无法使用 redux 工具包从 API 获取数据
- godot - 收到此错误“add_child:参数“p_child”为空”并且似乎无法追踪它
- python - 使用自定义方法修补方法时如何在测试中检索类属性?
- c# - Gridview中的JQuery如何在文本框在同一行更改时检查复选框
- sql - 如何在动态查询中使用整数变量
- memory-management - 将设备内存和内核分配的内存映射到同一个 vma
- sql - 雪花 SQL 中的 JSON 解析
- vb.net - Amazon Vendor Central - 如何创建散列工资单?