【问题标题】:Combining row vectors for data frame after using quantile function使用分位数函数后组合数据帧的行向量
【发布时间】:2018-08-21 07:36:10
【问题描述】:

新手问题。我运行了以下命令:

CI_95_outcomes_male

最后得到这个输出:

CI_95_outcomes_male X1 X2 X3 X4 95% 9629902039 0 2.968924e+15 2.968924e+15

我想将此向量与以下向量组合以得到 2X4 矩阵:

#

mean_outcomes_male

ylg_吸烟_simS 死亡_避免总数_cig 总数_税_ 9.62990 0.0000 2.78248 2.782480

我试过了:

CI_95_outcomes_male

感谢任何指导,谢谢!

【问题讨论】:

    标签: r dataframe quantile


    【解决方案1】:

    CI_95_outcomes_male

    我想你忘了把colnames 放在CI_95_outcomes_male 周围。但这里还有另一个问题。我假设mean_outcomes_male 是一个向量,在这种情况下colnames(mean_outcomes_male)NULL

    data.frame(mean_outcomes_male,CI_95_outcomes_male)

    即使CI_95_outcomes_male 正确,上述命令也会生成一个 4x5 数据框,第一列是 mean_outcomes_male 向量,第二列是第一个变量的 CI_95_outcomes_male 值(对每一行重复),...,第五列是您的第四个变量的 CI_95_outcomes_male 值(对每一行重复)。

    你需要做这样的事情:

    set.seed(42)
    
    # Generate a random dataset for outcomes_male_dt with 4 variables and n rows
    n <- 100
    outcomes_male_dt <- data.frame(x1=runif(n),x2=runif(n),x3=runif(n),x4=runif(n))
    
    # I'm assuming you want the 95th percentile of each variable in outcomes_male_dt and store them in CI_95_outcomes_male
    ptl <- .95  # if you want to add other percentiles you can replace this with something like "ptl <- c(.10,.50,.90,.95)" 
    CI_95_outcomes_male <- apply(outcomes_male_dt,2,quantile,probs=ptl)
    
    # I'm going to assume that mean_outcomes_male is a vector of means for all the variables in outcomes_male_dt
    mean_outcomes_male <- colMeans(outcomes_male_dt)
    
    # You want to end up with a 2x4 matrix - I'm assuming you meant row 1 will be the means, and row 2 will be the 95th percentiles, and the columns will be the variables
    want <- rbind(mean_outcomes_male, CI_95_outcomes_male)
    colnames(want) <- colnames(outcomes_male_dt)
    row.names(want) <- c('Mean',paste0("p",ptl*100)) # paste0("p",ptl*100) is equivalent to paste("p",ptl*100,sep="")
    want # Resulting matrix
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 2016-11-29
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2018-08-30
      • 1970-01-01
      相关资源
      最近更新 更多