r - 如何将 sapply 应用于使用 match.call 的函数?
问题描述
我正在使用一个现有函数,该函数用于match.call
捕获输入并使用此输入定义数据框。我想sapply
将字符串名称向量应用于与数据框中的变量名称匹配的函数。但是,该函数捕获sapply
i
,因此这不起作用。
任何指导将不胜感激。也对替代方法持开放态度sapply
。
最小的可重现示例:
# Generate data
dat = sapply(1:5, function(i){rnorm(n = 10, mean = i)})
dat = as.data.frame(dat)
> dat
V1 V2 V3 V4 V5
1 2.7305301 3.2459056 2.366443 3.274836 4.902216
2 0.3809082 2.5033985 3.095093 2.675995 7.397180
3 1.8283385 0.4956617 2.004782 3.985234 4.689735
4 0.8450546 2.1390986 5.277488 6.052577 5.167756
5 2.7092999 4.0838629 1.683245 5.094684 5.306989
6 1.0471351 2.0033031 1.031404 3.126332 3.519315
7 0.2491428 0.3844910 2.670281 4.141592 5.318283
8 0.3319631 3.0790678 3.653437 1.500079 4.567699
9 0.9759534 0.7928414 3.549303 4.948636 4.952653
10 0.8205076 1.2129117 2.418991 4.833864 5.170205
# Toy function with match call
toy <- function(x, dataset){
args <- as.list(match.call())
x <- eval(args$x, dataset)
if (class(x) == "character"){x <- get(x, dataset)}
newdat = data.frame(x)
return(newdat)
}
# Example use of toy
toy(x = "V1", dataset = dat)
x
1 2.7305301
2 0.3809082
3 1.8283385
4 0.8450546
5 2.7092999
6 1.0471351
7 0.2491428
8 0.3319631
9 0.9759534
10 0.8205076
# What I would like to do:
sapply(c("V1", "V2"), function(i){
toy(x = i, dataset = dat)
})
Error in eval(args$x, dataset) : object 'i' not found
解决方案
推荐阅读
- java - 在 Java 中执行方法子字符串时收到错误
- python - 我有一个我想使用的 .csv 文件,而不是手动输入详细信息以将“点击框”添加到标记点
- html - 使用边距定位图像
- c++ - 如何在cpp中访问父操作符
- c++ - 为什么通过定义另一个指针单元整个代码停止工作?
- ruby - 如何在我的应用程序 ruby on rails 中添加评论功能?
- node.js - 使用webpack时如何在vs代码中调试typescript文件
- scala - 如何将数据框拆分为不同的 df 并需要保存在不同的文件中?
- php - php中两个JSON字符串之间的区别并删除重复项?
- mysql - 创建计算列时出现“as”错误