Search code examples
rr-mosaic

R-Mosaic: Is there a mean.n function?


is there a mean.n function (just as in SPSS) in mosaic in R?

I have 3 columns of data (including "NA") and I want a new column to have the means of the 3 data points for each row. How do I do that?


Solution

  • rowMeans might be just what you are looking for. It will return the row-wise mean, make sure to select/subset the right columns.

    Here is an example

    # Load packages
    library(dplyr)
    
    # Example data
    ex_data = data.frame(A = rnorm(10), B = rnorm(10)*2, C = rnorm(10)*5)
    ex_data
    #>             A          B          C
    #> 1   0.2838024 -1.8784902 -2.7519131
    #> 2  -0.4090575  1.6457548  6.1643390
    #> 3   0.2061454  0.2103105  7.2798434
    #> 4  -1.5246471 -0.6071042 -7.2411695
    #> 5  -1.0461921 -2.6290405 -1.3840000
    #> 6  -1.4802151  1.9323571  5.8539328
    #> 7   0.1827485  0.1608848 -0.5157152
    #> 8  -0.3006229  2.8650122 -1.4393171
    #> 9   2.2981543 -0.2790727  2.6193970
    #> 10  1.0495951 -0.9061784 -4.4013859
    
    # Use rowMeans
    ex_data$abc_means = rowMeans(x = ex_data[1:3])
    ex_data
    #>             A          B          C   abc_means
    #> 1   0.2838024 -1.8784902 -2.7519131 -1.44886698
    #> 2  -0.4090575  1.6457548  6.1643390  2.46701208
    #> 3   0.2061454  0.2103105  7.2798434  2.56543308
    #> 4  -1.5246471 -0.6071042 -7.2411695 -3.12430691
    #> 5  -1.0461921 -2.6290405 -1.3840000 -1.68641084
    #> 6  -1.4802151  1.9323571  5.8539328  2.10202491
    #> 7   0.1827485  0.1608848 -0.5157152 -0.05736064
    #> 8  -0.3006229  2.8650122 -1.4393171  0.37502404
    #> 9   2.2981543 -0.2790727  2.6193970  1.54615953
    #> 10  1.0495951 -0.9061784 -4.4013859 -1.41932305
    

    You mentioned that you have NAs in your data, make sure to include na.rm = TRUE if appropriate.

    Created on 2021-04-02 by the reprex package (v0.3.0)