R - 循环通过矩阵列

时间:2017-11-09 16:02:15

标签: r matrix

我已经写了一个函数,根据贷款特征分期偿还贷款,并向我提供支付现金流的现值:

limits.h

给定一组(不同的)贷款和一个包含每个贷款的每个函数参数值的矩阵,我现在想创建一个循环,因为该函数循环遍历矩阵的每一列并给我输出功能。

任何人都可以帮助我完成这项工作吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

我肯定会建议你在第一篇文章的评论中考虑@Gregor的建议 - 避免在函数中进行全局赋值。也就是说,这就是我如何处理你的问题:

假设:对于您的数据,您使用的是数据框,其中每一行都映射到一个唯一的贷款,每个列条目都有一个参数(在我的示例中名为A,B和C),用于相应的行。

我的简单示例应该可以轻松扩展到您的问题:

df <- data.frame(A=c(1,0,3),B=c(3,3,3),C=c(4,3,0)) # Replace with your data

# Replace with your function
myFn <- function(A,B,C) {
  x <- (A+B)/C
  return(x)
  }

# Appends 'answer' to your dataframe with the answer correctly mapped to each loan
df$answer <- with(df,myFn(A=A,B=B,C=C))

如果您希望获得多个答案&#39;返回,将代码更改为:

df <- data.frame(A=c(1,0,3),B=c(3,3,3),C=c(4,3,0)) # Replace with your data

# Replace with your function
myFn <- function(A,B,C) {
  x <- (A+B)
  y <- C
  z <- x/y
  return(data.frame(A=A,B=B,C=C,numerator=x,denominator=y,answer=z))
  }

# Creates a new dataframe from the original with each 'multivariate' answer correctly mapped to each loan
df2 <- with(df,myFn(A=A,B=B,C=C))

# Examine your output:
head(df2)
str(df2)

可能有更优雅的解决方案,但这应该符合您的目的。