LCheng
LCheng

Reputation: 400

Buidling R package with issue loading data.table ".()" function

when building an R package that uses data.table as an attached package, the list() function of data.table ".()" always gives the error could not find function ".". While other functions from data.table were all recognized. Here is my .R page for the function that uses data.table:

#' Advanced Bar Plot with Statistics
#'
#' Creates an advanced bar plot with mean and standard error for specified categories
#' using ggplot2.
#'
#' @param data_frame A data frame containing the data for plotting.
#' @param col The name of the column for calculating statistics.
#' @param category1 The primary category for grouping data.
#' @param category2 The secondary category for grouping data (default is "Memory").
#' @param title The title for the plot (default is the value of category1).
#' @return A ggplot2 bar plot object with error bars.
#' @import data.table
#' @examples
#' df <- data.table(value = rnorm(100), dx = sample(c("Group1", "Group2"), 100, replace = TRUE), Memory = sample(0:1, 100, replace = TRUE))
#' quick_bar_plot2(df, "value", "dx", "Memory")
quick_bar_plot2 <- function(data_frame, col, category1, category2 = "Memory", title = category1){
  setDT(data_frame)

  # Dynamic column names: compute mean and standard error
  col_stats <- data_frame[, .(Mean_col = mean(get(col), na.rm = TRUE),
                              SE = sd(get(col), na.rm = TRUE)/sqrt(.N)),
                          by = c(category1, category2)]

  col_stats[, (category2) := factor(get(category2), levels = c(1, 0), labels = c("Impaired", "Not Impaired"))]

  # Create the plot
  # print(class(col_stats[[category2]]))
  # print(levels(col_stats[[category2]]))
  ggplot(col_stats, aes_string(x = category1, y = "Mean_col", fill = category2)) +
    geom_bar(stat = "identity", position = position_dodge()) +
    geom_errorbar(aes(ymin = Mean_col - SE, ymax = Mean_col + SE),
                  position = position_dodge(0.9), width = 0.25) +
    scale_fill_manual(name = category2, values = c("Impaired" = "#F8766D", "Not Impaired" = "#00BA38")) +
    # scale_fill_manual(name = category2, values = colors)
    labs(title = paste("Mean", gsub("_", " ", col), "by", title, "and", category2), # \n
         x = " ",
         y = paste("Mean", col)) +
    theme_minimal()
  # print(plot)
}

The function works fine when just using independently, but when I include it as a function in my R package, I got the following example error:

### ** Examples

df <- data.table(value = rnorm(100), dx = sample(c("Group1", "Group2"), 100, replace = TRUE), Memory = sample(0:1, 100, replace = TRUE))
quick_bar_plot2(df, "value", "dx", "Memory")
Error in .(Mean_col = mean(get(col), na.rm = TRUE), SE = sd(get(col), : could not find function "."

Upvotes: 0

Views: 94

Answers (0)

Related Questions