如何在R中对测试进行编程,以便它们能很好地打印?

时间:2019-05-28 00:48:38

标签: r pretty-print

<?php session_start(); error_reporting(0); $db = mysqli_connect('localhost', 'root', '', 'online_car_rental'); if (!isset($_SESSION['username'])) { $_SESSION['msg'] = "You must log in first"; header('location: login.php'); } if(isset($_GET['booking_id'])) { $item = $_GET['booking_id']; $querytotal_day = mysqli_query ($db,"SELECT total_day FROM car WHERE car_id = '$car_id'"); $querytotal_dayrow = mysqli_fetch_assoc ($querytotal_day) $car_id = $querytotal_dayrow["car_id"]; $total_daybooking = mysqli_query ($db,"SELECT total_daybooking FROM car WHERE car_id = '$car_id'"); $q = mysqli_fetch_assoc ($total_daybooking); $total_day = (int) $q["total_daybooking"]; $querytotal_dayint = (int) $querytotal_dayrow["total_day"]; $remainingtotal_day = $querytotal_dayint + $total_day; $barang = "DELETE From booking WHERE booking_id='$item'"; if ($db -> query($barang) === true) { echo '<script>alert("Delete successful!")</script>'; mysqli_query($db, "UPDATE car SET total_day = '$remainingtotal_day'"); } } if (isset($_GET['logout'])) { session_destroy(); unset($_SESSION['username']); header("location: login.php"); } include('server.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ONLINE CAR</title> <link rel="stylesheet" href="belumlogin.css"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="index.css"> </head> <body class="badan"> <ul> <div class ="content"> <center> <img src="car.jpg" alt="car" width="1500" height="250"> </center> </div> <p>ONLINE CAR RENTAL</p> <a href="add.php?logout='1'" style="color: red;">LOGOUT</a> <li><a href="booking.php">BOOKING</a></li> <li><a href="car.php">CAR</a></li> <li><a> Welcome <strong><?php echo $_SESSION['username']; ?></strong> </body> <body class="badan"> <div class = "container"> <div class = "index-box"> <div class = "row"> <div class = "col-md-12 index-mid"> <h2>CART</h2> <style> table, td, th { border: 1px solid black; padding: 8px; } table { border-collapse: collapse; width: 100%; } th{ background-color: #ddd; } td { height: 30px; vertical-align: bottom; } </style> </body> <table align='center' width='50%'> <tr> <th width='15%' align='center'>Image</th> <th width='15%' align='center'>Name</th> <th width='15%' align='center'>Total day booking</th> <th width='15%' align='center'>Total price (RM)</th> </tr> <?php $carr = $_SESSION['username']; $carrlike = mysqli_query($db, "SELECT * FROM users WHERE username = '$carr'"); $carrlikee = mysqli_fetch_assoc($carrlike); $intcarrlike = (int) $carrlike['id']; $query = mysqli_query($db,"SELECT car.car_image, car.car_name, booking.total_daybooking, booking.totalprice FROM 'car' INNER JOIN 'booking' ON car.car_id = booking.carID WHERE booking.custID = $intcarrlike" ); if(mysqli_num_rows($query) > 0) { while($row = mysqli_fetch_array($query)) { $car_id = $row['car_id']; $query2 = mysqli_query($db,"SELECT car_name FROM car WHERE car_id='$car_id'"); ?> <tr> <td width='15%' align='center'> <?php echo "<img src='".$row['car_image']."'width = '100' height ='100'>"; ?> </td> <th width='15%' align='center'><?php echo $row["car_name"]; ?> </td> <th width='15%' align='center'><?php echo $row["total_daybooking"]; ?> </td> <th width='15%' align='center'><?php echo $row["totalprice"]; ?> </td> <?php // delete Print "<td width='15%' align='center'><button onclick='deleteor(" . $row["booking_id"] . ")'>Delete</button></td>"; Print "<td width='15%' align='center'><button onclick='updatelist(" . $row["booking_id"] . ")'>Update</button></td>"; ?> </tr> <?php } //tutup while loop }else{ echo "0 Results"; } ?> </table> <?php //resit Print "<div align = 'right'><button style = 'width:100px' onClick='receipt(" . $id . ")'>Receipt</button></div>"; ?> <script> function deleteor( id ) { var r = confirm( "Are you sure you want to delete this order?" ); if ( r == true ) { window.location.assign( "cart.php?booking_id=" + id ); } } function updatelist( id ) { var r = confirm( "Are you sure you want to update this order?" ); if ( r == true ) { window.location.assign( "car.php?booking_id=" + id ); } } function receipt ( id ) { window.open("receipt.php?booking_id=" + id ); } </script> </html> 中的统计测试会生成列表,但是当您调用测试时,这些列表的打印会提供一种特殊的用户友好结构,以帮助读者。要了解我在说什么,请考虑一个使用R包中的t.test函数的示例。

stats

此对象是包含九个元素的列表,其中一些是通过属性命名的。但是,当我打印#Run a T-test on some example data X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39); Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50); TEST <- stats::t.test(X,Y); #Show structure of the TEST object str(TEST); List of 9 $ statistic : Named num -0.134 ..- attr(*, "names")= chr "t" $ parameter : Named num 10.2 ..- attr(*, "names")= chr "df" $ p.value : num 0.896 $ conf.int : num [1:2] -12.3 10.9 ..- attr(*, "conf.level")= num 0.95 $ estimate : Named num [1:2] 32.8 33.5 ..- attr(*, "names")= chr [1:2] "mean of x" "mean of y" $ null.value : Named num 0 ..- attr(*, "names")= chr "difference in means" $ alternative: chr "two.sided" $ method : chr "Welch Two Sample t-test" $ data.name : chr "X and Y" - attr(*, "class")= chr "htest" 对象时,返回的信息的结构与列表的标准打印不同。

TEST

如您所见,此打印输出比列表的标准打印更加用户友好。我希望能够在#Print the TEST object TEST; Welch Two Sample t-test data: X and Y t = -0.13444, df = 10.204, p-value = 0.8957 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -12.27046 10.87046 sample estimates: mean of x mean of y 32.8 33.5 中对统计测试进行编程,以生成与上述输出类似的输出列表,但是以这种用户友好的方式进行打印。


我的问题:为什么R用这种特殊方式打印列表R的输出?如果我创建了统计测试的输出列表(例如上述内容),如何设置对象以这种方式打印?

2 个答案:

答案 0 :(得分:3)

使用以下最能满足您需求的方法。

        $atts = shortcode_atts(
            array(
                'itemcode'  => '',
            ),
            $atts, 'products_catalog'
        );


        $woocommerce_loop['columns'] = 1;

        $meta_query_args = array(
            array(
                'key' => 'neproductinfo-ne_item_code',
                'value' => $atts['itemcode'],
                'compare'   => '='
            )
        );
        $meta_query = new WP_Meta_Query( $meta_query_args );  


        $products = new WP_Query( array (
            'post_type'         => 'product',
            'post_status'       => 'publish',
            //'posts_per_page'    => 1,
            'meta_query'        => $meta_query
        ));

要解决OP的后续问题:

“每个” 类数据具有一种打印方法。正如我在答案中概述的那样,X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39) Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50) TEST <- stats::t.test(X,Y) #default; printing data of htest class print(TEST) #printing every element of the list lapply(TEST, print) print.listof(TEST) #printing the results as a dataframe broom::tidy(TEST) #output of this one is included just for illustration # A tibble: 1 x 10 estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high method alternative <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <chr> 1 -0.7 32.8 33.5 -0.134 0.896 10.2 -12.3 10.9 Welch Two Sample t-test two.sided 函数着眼于print,由于它是TEST的类,因此它使用 print.htest

htest

在我刚开始的R会话中,我有185种不同的方法。加载库时,数量会增加。

如果您想更深入地研究,则需要查看class(TEST) # [1] "htest" head(methods(print)) # [1] "print.acf" "print.AES" "print.all_vars" "print.anova" # [5] "print.anova.lme" "print.ansi_string" 的源代码,可以在这里找到:R source code on GitHub

答案 1 :(得分:0)

此答案是由其他用户的有用评论和答案组合而成的,但是我想在此处给出一个详尽的答案,以使事情更明确,以使尚未熟悉其中一些问题的用户受益。由t.test函数创建的对象是类htest的对象,并且这种类型的对象在全局环境中的print.htest设置下具有特殊的打印方法。该打印方法从列表中提取信息,但是以您在问题输出中看到的用户友好方式打印它。

如果您想为自己编程的新统计测试复制这种类型的打印,则需要构造新测试,以使其输出htest对象以及所需的元素。列表,以及所需的类。这是另一个answer的示例,其中Tarone (1979)中列出的假设检验被编程为htest对象:

Tarone.test <- function(N, M) {

    #Check validity of inputs
    if(any(M > N)) { stop("Error: Observed count value exceeds binomial trials"); }

    #Set hypothesis test objects
    method      <- "Tarone's Z test";
    alternative <- "greater";
    null.value  <- 0;
    attr(null.value, "names") <- "dispersion parameter";
    data.name   <- paste0(deparse(substitute(M)), " successes from ", 
                          deparse(substitute(N)), " counts");

    #Calculate test statistics
    estimate    <- sum(M)/sum(N);
    attr(estimate, "names") <- "proportion parameter";

    S           <- sum((M - N*estimate)^2/(estimate*(1 - estimate)));
    statistic   <- (S - sum(N))/sqrt(2*sum(N*(N-1))); 
    attr(statistic, "names") <- "z";

    p.value     <- 2*pnorm(-abs(statistic), 0, 1);
    attr(p.value, "names") <- NULL;

    #Create htest object
    TEST        <- list(statistic = statistic, p.value = p.value, estimate = estimate, 
                        null.value = null.value, alternative = alternative, 
                        method = method, data.name = data.name);
    class(TEST) <- "htest";

    TEST; }

在此示例中,该函数计算htest对象的所有必需元素,然后将该对象创建为具有该类的列表。在代码中包括命令class(TEST) <- "htest"很重要,这样创建的对象不仅是常规列表。包含该命令将确保输出对象属于适当的类,因此它将以用户友好的方式进行打印。要看到这一点,我们可以生成一些数据并应用测试:

#Generate example data
N <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
M <- c( 9, 10, 22, 15,  8, 19, 16, 19, 15, 10);

#Apply Tarone's test to the example data
TEST <- Tarone.test(N, M);
TEST;

        Tarone's Z test

data:  M successes from N counts
z = 2.5988, p-value = 0.009355
alternative hypothesis: true dispersion parameter is greater than 0
sample estimates:
proportion parameter 
           0.4359756

在这里,我们看到我们新创建的假设检验功能为我们提供了与t.test类似的用户友好结构的输出。在此示例中,我们为测试方法和测试元素指定了不同的名称,这些名称在打印时显示在描述性输出中。