使用R中的函数执行多个任务

时间:2016-05-05 17:02:32

标签: r function

我想编写一个函数,它将采用两个分类变量并创建和显示马赛克图,计数表,行表百分比,然后最终显示卡方检验。假设我有关于某人的婚姻状况(已婚/未婚)以及他们是否吸烟(是/否)的数据。我希望它创建这两个变量的马赛克图,然后显示这两个变量的计数/行百分比,最后进行卡方检验。

我尝试过以下方法:

Fnct <- function(x, y) {
    # Will create mosaic plot, but the labels show up incorrectly
    plot <- mosaicplot(~x + y, color=TRUE, main = "Mosaic Plot", xlab = x, ylab = y)

    #creates a 2by2 table and stores it in my table
    mytable <- table(x, y)
    mytable2 <- prop.table(mytable, 1)

    chi <- chisq.test(mytable)

    return(c(plot, mytable2, chi))
}

Fnct(Data$Marital, Data$Smoker)

当我输出数据时,它会输出马赛克图,但标签不正确。他们反复重复治疗水平,但不仅仅是列名。它也不能正确输出计数或卡方检验。我做错了什么?

1 个答案:

答案 0 :(得分:2)

你不应该让它返回一个向量。相反,让它像这样返回list

Fnct <- function(x,y) {

    #just plot it, don't return it
    mosaicplot(~x + y,color=TRUE,main = "Mosaic Plot", 
    xlab = substitute(x), 
    ylab = substitute(y))

    mytable2 <-prop.table(table(x, y), 1)

    chi <- chisq.test(table(x,y))

    #return a named list
    return(list(
                'Row Percentages' = mytable2,
                'Chi-squared test' = chi))
}

然后,您希望以下列方式调用它,以使标签正确显示:

with(mydata, Fnct(x, y))

以下是它的工作原理:

set.seed(1)
df <- data.frame(A = sample(c('a','b'), 100, replace = T),
                 B = sample(c('foo','bar','haz'), 100, replace = T))
with(df, Fnct(A,B))

$`Row Percentages`
   y
x         bar       foo       haz
  a 0.5000000 0.2307692 0.2692308
  b 0.2916667 0.3541667 0.3541667

$`Chi-Squared Test`

    Pearson's Chi-squared test

data:  table(x, y)
X-squared = 4.5998, df = 2, p-value = 0.1003

enter image description here