You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将自定义R函数的输出值转换为DataFrame?附函数代码

Solution to Convert Your R Function Output to a DataFrame

Got it, let's adjust your function so it returns a structured DataFrame instead of a plain list. The fix is straightforward since your existing code already calculates all the values we need—we just need to wrap the resulting list in a DataFrame constructor.

First, let's clean up and modify your function. I noticed the original code was missing a closing parenthesis for the list() call, so I'll fix that too:

f <- function(x) { 
  bruto <- x*1.289 
  LC <- bruto*1.0124 
  npd <- max(470 - 0.16*max(0,(bruto - 600)),0) 
  lubos <- 5*850*1.289*1.05^3 
  tax_base <- max(0,(bruto-npd)) 
  gpm <- ifelse(bruto<=lubos, tax_base*0.21, lubos *0.21+(bruto-lubos)*0.25) 
  sodra <- min(max(bruto*0.185, 600*0.185), lubos * 0.185) 
  db <- bruto*0.0124 
  neto <- bruto - gpm - sodra 
  
  # Create a named list of results
  result_list <- list(
    old_bruto = x, 
    new_bruto = bruto, 
    npd = npd, 
    gpm = gpm, 
    sodra = sodra, 
    neto = neto, 
    ITR = ((LC - neto)/LC)
  )
  
  # Convert the list to a base R DataFrame and return it
  as.data.frame(result_list)
}

How It Works:

  • We first assemble all calculated values into a named list (this keeps column names intact in the final DataFrame).
  • as.data.frame(result_list) converts the list into a 1-row DataFrame when you pass a single x value (e.g., f(500)). If you pass a vector of x values (like f(c(500, 600, 700))), it will automatically create a multi-row DataFrame with one row per input value—all your calculations are already vectorized, so this works seamlessly.

Bonus: Tidyverse-Style Tibble (Optional)

If you prefer the cleaner output of a tibble (from the tidyverse), replace as.data.frame() with tibble::as_tibble():

library(tibble)

f <- function(x) { 
  bruto <- x*1.289 
  LC <- bruto*1.0124 
  npd <- max(470 - 0.16*max(0,(bruto - 600)),0) 
  lubos <- 5*850*1.289*1.05^3 
  tax_base <- max(0,(bruto-npd)) 
  gpm <- ifelse(bruto<=lubos, tax_base*0.21, lubos *0.21+(bruto-lubos)*0.25) 
  sodra <- min(max(bruto*0.185, 600*0.185), lubos * 0.185) 
  db <- bruto*0.0124 
  neto <- bruto - gpm - sodra 
  
  result_list <- list(
    old_bruto = x, 
    new_bruto = bruto, 
    npd = npd, 
    gpm = gpm, 
    sodra = sodra, 
    neto = neto, 
    ITR = ((LC - neto)/LC)
  )
  
  as_tibble(result_list)
}

Testing this with f(500) will give you a nicely formatted tibble instead of a base DataFrame, which is easier to read in the console.

内容的提问来源于stack exchange,提问作者Justas Mundeikis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:35:37