R - 定义一个函数,它不是将参数识别为对象,而是将其识别为调用的一部分 [英] R - Defining a function which recognises arguments not as objects, but as being part of the call

查看:50
本文介绍了R - 定义一个函数,它不是将参数识别为对象,而是将其识别为调用的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个在 R 中返回图形对象的函数.这个想法是,我可以使用 for 循环或 lapply 多次使用不同的参数调用这个函数 函数,然后在 gridExtra::grid.arrange 中绘制 grobs 的列表.然而,我还没有走到那一步.我在将参数识别为调用的一部分时遇到了麻烦.我已经制作了一些代码来向您展示我的问题.我已经尝试引用和取消引用参数,在函数中使用 unqoute() (在用户定义的函数中出现找不到对象"错误,eval() 函数?),使用 eval(parse())代码> (R - 如何使用参数列表过滤数据以生成多个数据框和图形),使用 !! 等.但是,我似乎无法让它工作.有谁知道我应该如何处理这个问题?

I'm trying to define a function which returns a graphical object in R. The idea is that I can then call this function with different arguments multiple times using an for loop or lapply function, then plotting the list of grobs in gridExtra::grid.arrange. However, I did not get that far yet. I'm having trouble with r recognising the arguments as being part of the call. I've made some code to show you my problem. I have tried quoting and unquoting the arguments, using unqoute() in the function ("Object not found" error within a user defined function, eval() function?), using eval(parse()) (R - how to filter data with a list of arguments to produce multiple data frames and graphs), using !!, etc. However, I can't seem to get it to work. Does anyone know how I should handle this?

library(survminer)
library(survival)

data_km <- data.frame(Duration1 = c(1,2,3,4,5,6,7,8,9,10),
                      Event1 = c(1,1,0,1,1,0,1,1,1,1),
                      Duration2 = c(1,1,2,2,3,3,4,4,5,5),
                      Event2 = c(1,0,1,0,1,1,1,0,1,1),
                      Duration3 = c(11,12,13,14,15,16,17,18,19,20),
                      Event3 = c(1,1,0,1,1,0,1,1,0,1),
                      Area = c(1,1,1,1,1,2,2,2,2,2))

# this is working perfectly
ggsurvplot(survfit(Surv(Duration1, Event1) ~ Area, data = data_km))
ggsurvplot(survfit(Surv(Duration2, Event2) ~ Area, data = data_km))
ggsurvplot(survfit(Surv(Duration3, Event3) ~ Area, data = data_km))

myfun <- function(TimeVar, EventVar){
  ggsurvplot(survfit(Surv(eval(parse(text = TimeVar), eval(parse(text = EventVar)) ~ Area, data = data_km))
}

x <- myfun("Duration1", "Event1")
plot(x)

推荐答案

你需要学习一些关于语言计算的教程.我喜欢用基础 R 来做,例如,使用 bquote.

You need to study some tutorials about computing on the language. I like doing it with base R, e.g., using bquote.

myfun <- function(TimeVar, EventVar){
  TimeVar <- as.name(TimeVar)
  EventVar <- as.name(EventVar) 

  fit <- eval(bquote(survfit(Surv(.(TimeVar), .(EventVar)) ~ Area, data = data_km)))
  ggsurvplot(fit)
}

x <- myfun("Duration1", "Event1")
print(x)
#works

这篇关于R - 定义一个函数,它不是将参数识别为对象,而是将其识别为调用的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆