如何用管道操作将ineq函数计算的基尼系数存入数据框?
Solution
You can streamline this into a single pipe chain using either base R's data.frame() or dplyr's summarize(). Here are two working approaches:
Approach 1: Using pipes with data.frame()
library(ineq) library(dplyr) DATA_REFORM <- rnorm(1000, 3, .25) INEQ_TOTAL_INCOME_OUTPUT <- DATA_REFORM %>% ineq(type = "Gini", na.rm = TRUE) %>% round(4) %>% data.frame("Gini coefficient of pre-tax income" = .)
Approach 2: Using dplyr::summarize() (more idiomatic for data frames)
INEQ_TOTAL_INCOME_OUTPUT <- DATA_REFORM %>% summarize( "Gini coefficient of pre-tax income" = round(ineq(., type = "Gini", na.rm = TRUE), 4) )
Why your original code failed
Your attempt had two main issues:
- You tried to assign a variable (
gx <-) inside thedata.frame()call while using a pipe, which breaks the pipe's natural flow—pipes pass the output of the previous expression, not a manually assigned variable. - Referencing
gx[1,1]after the pipe doesn't work becausegxisn't defined in that context yet, and the pipe expects a function to process the prior result.
Both corrected approaches avoid these problems by letting the pipe pass data through each step naturally: either using the dot (.) to reference the previous result, or embedding the ineq() call directly inside summarize().
Testing either method will give you a single-row data frame with your desired Gini coefficient value, e.g.:
Gini coefficient of pre-tax income 1 0.0477
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

