在 R 中使用 apply 和assign [英] using apply with assign in R

查看:32
本文介绍了在 R 中使用 apply 和assign的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例:

Vars <- c("car","bike","lorry")
Dat <- c(10,20,22)

for (i in 1:length(Vars)){
  assign(Vars[i],Dat[i])
}

这里,我想在根据Vars 中的条目和Dat 中的值命名的工作区中生成三个变量.目前我正在使用循环,但我一直在尝试通过使用 apply 来删除循环,这样做的最佳方法是什么?

Here, I would like to generate three variables in the workspace named according to the entries in Vars and the values in Dat. At the moment I am using a loop, but I have been trying to remove the loop by using apply, how would be the best way of doing this?

推荐答案

这是一个很好的例子,说明何时使用 for 循环而不是 apply.
最好的解决办法是保持原样.

This is a great example of when to use a for loop instead of an apply.
The best solution is to leave it as it is.

如果你真的想使用 *ply 循环,使用 mapply

if you really want to use an *ply loop, use mapply

 mapply(assign, Vars, Dat, MoreArgs=list(envir=parent.frame()))

这篇关于在 R 中使用 apply 和assign的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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