r - R用户定义函数:新数据框名称作为函数参数
问题描述
我在编写用户定义的函数来操作 R 中的数据帧时遇到了一个问题。我想编写带有 2 个参数的函数:输入数据帧的名称和将在函数中创建的数据帧的名称。以下是使用 mtcars 数据集的示例:
subset_high_hp <- function(full_table, only_highHP) {
only_highHP <<- full_table %>%
filter(hp > 200)
}
subset_high_hp(mtcars, mtcars_highhp)
subset_high_hp 现在创建一个名为 only_highHP 的数据框,而不是所需的 mtcars_highhp。我知道这是一个非常基本的问题,但我是 R 新手,并且真的很难找到正确的文档。谁能指出我正确的方向?
解决方案
我认为您可以使用assign
此技巧:
subset_high_hp <- function(full_table, df_name) {
sub_df <- full_table %>%
filter(hp > 200)
assign(x = df_name, value = sub_df, envir = globalenv())
}
subset_high_hp(full_table = mtcars, df_name = "mtcars_highhp")
mtcars_highhp
mpg cyl disp hp drat wt qsec vs am gear carb
1 14.3 8 360 245 3.21 3.570 15.84 0 0 3 4
2 10.4 8 472 205 2.93 5.250 17.98 0 0 3 4
3 10.4 8 460 215 3.00 5.424 17.82 0 0 3 4
4 14.7 8 440 230 3.23 5.345 17.42 0 0 3 4
5 13.3 8 350 245 3.73 3.840 15.41 0 0 3 4
6 15.8 8 351 264 4.22 3.170 14.50 0 1 5 4
7 15.0 8 301 335 3.54 3.570 14.60 0 1 5 8
推荐阅读
- php - PHP不会将指定的变量发送到我的数据库,但是当我手动填写时会发送数据到数据库
- boolean-logic - 为什么(非真非真或非真非真)出来为真?
- javascript - 是否在夏令时显示正确时间
- logstash - Logstash:如何改变所有文本字段,使其短于 N
- amazon-web-services - AWS 自动扩展所需的容量更改
- r - R ggplot 如何选择具有 2 个值的栅格的颜色
- rabbitmq - 代理如何确保消息只被一个消费者消费?
- c# - 使用 C# 和 RestSharp 正确设置嵌套字典
- typo3 - TYPO3 8.7.32:向社交链接添加图标
- reactjs - 从对象数组中提取数据