在3个值的数据框上循环运行函数

时间:2019-03-03 08:16:42

标签: r function loops lapply

给出的功能:

hmin = function (H,M,s) {
H - ((2*9.8*M)/1.5*s))
}

# Create a data frame to test One-at-A-Time sensitivity analysis
# Keep H and M constant, varying s
# H = 50, M = 70.5, s = 20 to 40
s1 <- numeric(length = 20)
s1 [1:21] <- c(20:40)

H1 <- c(rep(50,length(s1)))
M1 <- c(rep(70.5, length(s1)))

dataframe1 <- data.frame(H1,M1,s1)

现在有了这个数据框,如何对数据框1中的变量运行hmin函数,并将输出hmin存储在向量中以绘制小节图。

尝试使用:

lapply(dataframe1, hmin (H1,M1,s1), dataframe1)

但是它不起作用。

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:2)

  

我的预期输出只是使用该函数运行变量的数据框并将其保存在向量中后返回hmin值。我该怎么做呢?

由于函数是矢量化的,所以请执行以下操作:

result = hmin(H = dataframe1$H1, M = dataframe1$M1, s = dataframe1$s1)

# same thing, using the with() helper function to save typing
result = with(dataframe1, hmin(H = H1, M = M1, s = s1))

答案 1 :(得分:0)

如果使用dplyr

> library(dplyr)
> dataframe1 <- data.frame(H1,M1,s1)
> hmin <- function(H,M,s) {
+   H - ((2*9.8*M)/1.5*s)
+ }
> dataframe1 %>%
+   mutate(hminscores = hmin(H1, M1, s1))
   H1   M1 s1 sensitivity
1  50 70.5 20    -18374.0
2  50 70.5 21    -19295.2
3  50 70.5 22    -20216.4
4  50 70.5 23    -21137.6
5  50 70.5 24    -22058.8
6  50 70.5 25    -22980.0
7  50 70.5 26    -23901.2
8  50 70.5 27    -24822.4
9  50 70.5 28    -25743.6
10 50 70.5 29    -26664.8
11 50 70.5 30    -27586.0
12 50 70.5 31    -28507.2
13 50 70.5 32    -29428.4
14 50 70.5 33    -30349.6
15 50 70.5 34    -31270.8
16 50 70.5 35    -32192.0
17 50 70.5 36    -33113.2
18 50 70.5 37    -34034.4
19 50 70.5 38    -34955.6
20 50 70.5 39    -35876.8
21 50 70.5 40    -36798.0

如果只需要向量,还可以使用apply

> hminscores <- apply(dataframe1, 1, function(x) {
+   hmin(x[1], x[2], x[3])
+ })
> hminscores
 [1] -18374.0 -19295.2 -20216.4 -21137.6 -22058.8 -22980.0 -23901.2 -24822.4 -25743.6
[10] -26664.8 -27586.0 -28507.2 -29428.4 -30349.6 -31270.8 -32192.0 -33113.2 -34034.4
[19] -34955.6 -35876.8 -36798.0