映射基础知识? - 如何从两个向量和一个函数创建一个矩阵
我正在尝试创建一个 data.frame 来创建图表。我有一个函数和两个向量,我想将它们用作两个输入。这有点简化,但基本上我所拥有的是:
relGPA <- seq(-1.5,1.5,.2)
avgGPA <- c(-2,0,2)
f <- function(relGPA, avgGPA) 1/(1+exp(sum(relGPA*pred.model$coef[1],avgGPA*pred.model$coef[2])))
我想要的只是一个 data.frame,其中 3 列用于 avgGPA 值,16 行用于 relGPA 值以及单元格中的结果值。
对于这是多么基本的事情,我深表歉意,但我向你保证,我已经尽力在没有你的帮助的情况下实现这一点。我已经尝试遵循 sapply 和 mapply 手册页上的示例,但我对 R 有点太陌生,无法了解我正在尝试做什么。
谢谢!
I am trying create a data.frame from which to create a graph. I have a function and two vectors that I want to use as the two inputs. This is a bit simplified, but basically all I have is:
relGPA <- seq(-1.5,1.5,.2)
avgGPA <- c(-2,0,2)
f <- function(relGPA, avgGPA) 1/(1+exp(sum(relGPA*pred.model$coef[1],avgGPA*pred.model$coef[2])))
and all I want is a data.frame with 3 columns for the avgGPA values, and 16 rows for the relGPA values with the resulting values in the cells.
I apologize for how basic this is, but I assure you I have tried to make this happen without your assistance. I have tried following the examples on the sapply and mapply man pages, but I'm just a little too new to R to see what I'm trying to do.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无法使用所提供的信息进行测试,但这应该可行:
当您想要生成组合时,另一个有用的函数是
expand.grid
,这将为您提供“长形式”:长形式是什么网格和 ggplot 将期望作为更高级别绘图的输入格式。
编辑:可能需要构造一个更具体的方法来将列引用传递给函数,如 djhurio 所指出的和 Sam Swift 使用
Vectorize
策略(已解决)。在apply
的情况下,sum
函数可以像上面描述的那样开箱即用,但除法运算符则不然,所以这里有一个可以推广的进一步示例具有多个参数的更复杂的函数。程序员所需要的只是“apply()”-ed”函数中适当参数的列号,因为(不幸的是)列名称没有传递到x
参数:Edit2 : (2013-01-05) 一年后看到这个,我意识到 SamSwift 的函数可以通过使其主体使用“+”而不是
sum
进行矢量化:Cannot be tested with the information offered, but this should work:
Another useful function when you want to generate combinations is
expand.grid
and this would get you the "long form":The long form is what lattice and ggplot will expect as input format for higher level plotting.
EDIT: It may be necessary to construct a more specific method for passing column references to the function as pointed out by djhurio and (solved) by Sam Swift with the
Vectorize
strategy. In the case ofapply
, thesum
function would work out of the box as described above, but the division operator would not, so here is a further example that can be generalized to more complex functions with multiple arguments. All the programmer needs is the number of the column for the appropriate argument in the "apply()"-ed" function, because (unfortunately) the column names are not carried through to thex
argument:Edit2: (2013-01-05) Looking at this a year later, I realized that SamSwift's function could be vectorized by making its body use "+" instead of
sum
: