Search code examples
rdataframesummary

Creating data frame from summary(); Error in dimnames(x) <- dnx : 'dimnames' applied to non-array


For the love of me, I don't understand why this does not work:

x = c(3, 5, 3, 100, 5, -9, 10, 24)
x_summary <- summary(x)
x_names <- names(x_summary)
x_summary <- unname(x_summary)
xdf <- data.frame(Statistics = x_names, Value = x_summary)

I thought the named vector from using summary() was the issue at first. But I don't understand why this yields the error: Error in dimnames(x) <- dnx : 'dimnames' applied to non-array


Solution

  • class(x_summary) is of type "summaryDefault" "table" which seems to provide difficulties for data.frame. Either covert the class, e.g. as.numeric(x_summary)/as.vector(x_summary) or use other packages, e.g. summary(x) |> broom::tidy(). Note that tibble::tibble(Statistics = x_names, Value = x_summary) provides the dataframe you are looking for, but be careful with the class of x_summary.

    data.frame(Statistics = x_names, Value = as.numeric(x_summary))
    
    Statistics   Value
    1       Min.  -9.000
    2    1st Qu.   3.000
    3     Median   5.000
    4       Mean  17.625
    5    3rd Qu.  13.500
    6       Max. 100.000