定义包含for循环的函数
我有两个数据帧 一个df1具有坡度和截距列,另一个df2具有索引列,即行号 我希望将一个基于df1参数的函数应用于df2中的整个索引列。我不希望函数混合和匹配斜率和截距,也就是说,我希望确保函数始终使用df1中相同列的斜率和截距 我试着这么做定义包含for循环的函数,r,R,我有两个数据帧 一个df1具有坡度和截距列,另一个df2具有索引列,即行号 我希望将一个基于df1参数的函数应用于df2中的整个索引列。我不希望函数混合和匹配斜率和截距,也就是说,我希望确保函数始终使用df1中相同列的斜率和截距 我试着这么做 my_function <- function(x) {for (i in df1$slope) for (j in df1$intercept) {((i*x)+j)}} df3 <- for (k in df2$Index) {my_fu
my_function <- function(x) {for (i in df1$slope) for (j in df1$intercept) {((i*x)+j)}}
df3 <- for (k in df2$Index) {my_function(k)}
df3
以下是我需要的输出:
index baseline_t_1 baseline_t_2 baseline_t_3
1 0.51 0.39 0.23
2 0.52 0.38 0.26
3 0.53 0.37 0.29
4 0.54 0.36 0.32
5 0.55 0.35 0.35
我做错了什么
谢谢 试试这个:
将三个带值的参数同时传递给Map中定义的匿名函数
可能是这样的:鉴于问题中没有数据和预期结果,我不确定您更喜欢哪一个
lapply( df2$index, function(index){
unlist( Map( function(slope, intercept) (index * slope ) + intercept,
slope = df1$slope, intercept = df1$intercept) )
})
欢迎来到SO!请给出输入数据和预期输出的示例。另外,请阅读以下内容:我很难想象如何将数据帧转换为预期输出。你能分享你的数据样本吗?试试dputheaddf1并将结果复制到问题中,然后展示你期望的结果是什么样的?非常感谢你的Sathish!你的第二个建议正是我需要的。
Map( function(index, slope, intercept) (index * slope ) + intercept,
index = df2$Index, slope = df1$slope, intercept = df1$intercept)
lapply( df2$index, function(index){
unlist( Map( function(slope, intercept) (index * slope ) + intercept,
slope = df1$slope, intercept = df1$intercept) )
})