繁体   English   中英

R-如何为同一变量的多个值运行代码?

[英]R- How to run code for multiple values of same variable?

假设我在 R 中运行一些公式,并且我有一个变量 k。 在我的实际情况中,它是一个税收水平,但就本示例而言,它只能是 2 或 3。我想创建一个代码来运行变量的两个值的公式(k = 2,k = 3)并将两种情况的 output 放在一个表中(我喜欢使用 knitr 的 kableExtra 包)。 出于效率的目的,我不想复制和粘贴公式(在实际情况下它是一个相当长的块)。

我怎么能这样做?

> k equals 2 *and* 3
> "if" does not refer to an if statement. It is just an explanatory placeholder. 

k <- 2 
firstvariable = k*100
secondvariable = firstvariable/2

data1 <- data.frame(secondvariable (if k = 2), firstvariable (if k = 1))

library(kableExtra)
table <- kbl(data1, caption = "Both values") 
table

这是sapply()的情况。 sapply() function 允许您在向量中的每个元素上运行相同的 function。 如果 function 返回两个值,则sapply()创建一个矩阵,您可以轻松地将其转换为表格。

k <- c(2,3)
my_fun <- function(x) {
  c(firstvariable = x * 100, secondvariable = x * 50)
}
sapply(k, my_fun)

               [,1] [,2]
firstvariable   200  300
secondvariable  100  150

然后,您可以使用cbind()来组装您的数据框。 您需要先用t()转置矩阵。

cbind(data.frame(k), t(sapply(k, my_fun)))

  k firstvariable secondvariable
1 2           200            100
2 3           300            150

现在你可以 go 做任何你想做的事。

由于乘法是向量化的,因此您可以直接对向量执行此计算。

create_data <- function(k) {
  tibble::tibble(k, firstvariable = k * 100, secondvariable = firstvariable/2)  
}

result <- create_data(c(2, 3))
result
# A tibble: 2 x 3
#      k firstvariable secondvariable
#  <dbl>         <dbl>          <dbl>
#1     2           200            100
#2     3           300            150

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM