代码之家  ›  专栏  ›  技术社区  ›  remo

R:带子集的T-统计量

  •  0
  • remo  · 技术社区  · 2 年前

    我希望有一个表作为ouptut,其中我有某些变量的均值差异和基于我的数据的两个特定子集之间的t统计。

    我有以下数据:

    structure(list(Name = c("A", "A", "A", "A", "B", "B", "B", "B", 
    "C", "C", "C", "C", "D", "D", "D", "D"), Date = c("20.10.2018", 
    "30.09.2018", "25.11.2019", "23.10.2020", "20.03.2018", "30.07.2018", 
    "25.08.2019", "23.10.2020", "20.12.2018", "30.01.2018", "25.02.2019", 
    "23.06.2020", "20.11.2018", "30.12.2018", "25.11.2019", "23.09.2020"
    ), Return = c(0.01, 0.05, 0.08, 0.07, 0.04, 0.03, 0.01, 0.03, 
    0.03, 0.05, 0.06, 0.07, 0.07, 0.04, 0.06, 0.08), Age = c(5L, 
    5L, 6L, 7L, 8L, 8L, 9L, 10L, 4L, 4L, 5L, 6L, 1L, 1L, 2L, 3L), 
        Size = c(53336L, 75768L, 86548L, 94567L, 40234L, 40240L, 
        50243L, 60352L, 5069L, 6069L, 7092L, 8024L, 2456L, 3046L, 
        4056L, 5600L), Rating = c(1L, 1L, 1L, 2L, 5L, 5L, 3L, NA, 
        4L, 5L, 4L, 5L, NA, 4L, 5L, 4L)), class = "data.frame", row.names = c(NA, 
    -16L))
    

    更具体地说,我想有一个表,其中我有一个t-统计数据,用于变量之间的每一个差异——回报率、年龄和大小,以及评级为1和5的观察结果。t统计数据应位于1级和5级之间,并应包括表示p值的星星。

    我尝试使用T.测试函数,但我只使用子组有困难,并且在评级1和评级5之间的中间创建T统计列。

    输出的布局应如下所示:

    structure(list(c("Return", "Age", "Size"), `Mean Rating 1` = c(NA, 
    NA, NA), `t-statistics including p-value (indicated as stars)` = c(NA, 
    NA, NA), `Mean Rating 5` = c(NA, NA, NA)), class = "data.frame", row.names = c(NA, 
    -3L))
    

    有人能帮我查一下密码吗?

    提前非常感谢。

    1 回复  |  直到 2 年前
        1
  •  3
  •   jay.sf    2 年前

    你可以很容易地绕一圈 subset= .

    t(with(mtcars, sapply(unique(cyl), \(i) t.test(am, subset=cyl == i))))
    #      statistic parameter p.value      conf.int  estimate null.value stderr     alternative method              data.name
    # [1,] 4.605489  31        6.632258e-05 numeric,2 0.40625  0          0.08820997 "two.sided" "One Sample t-test" "am"     
    # [2,] 4.605489  31        6.632258e-05 numeric,2 0.40625  0          0.08820997 "two.sided" "One Sample t-test" "am"     
    # [3,] 4.605489  31        6.632258e-05 numeric,2 0.40625  0          0.08820997 "two.sided" "One Sample t-test" "am"  
    

    更具体地说,对于您的数据,您可以这样做:

    tcols <- c('Return', 'Age', 'Size')
    r <- t(with(subset(dat, Rating %in% c(1, 5)), 
         sapply(setNames(tcols, tcols), \(i) unlist(
           t.test(reformulate('Rating', i))[
             c('estimate', 'statistic', 'p.value')]
           ))))
    cbind(as.data.frame(r),
          ' '=c("   ", "*  ", "** ", "***")[
            rowSums(outer(r[, 'p.value'], c(Inf, 0.05, 0.01, 0.001), `<`))])
    #        estimate.mean in group 1 estimate.mean in group 5 statistic.t   p.value    
    # Return             4.666667e-02                     0.05  -0.1552301 0.8883096    
    # Age                5.333333e+00                     5.60  -0.2198599 0.8353634    
    # Size               7.188400e+04                 19724.60   4.0457818 0.0109848 *  
    

    笔记 R>=4.1已使用。