Skip to content

Add way to convert list of content objects from content_search() into a data frame #451

@toph-allen

Description

@toph-allen

search_content() returns a list of content objects from the server (currently as a plain list). It's useful to turn this into a data frame sometimes.

Could add as.data.frame() and as_tibble() methods like what we did for integrations.

connectapi/R/get.R

Lines 623 to 679 in dc55d83

#' Convert usage data to a data frame
#'
#' @description
#' Converts an object returned by [get_usage()] into a data frame with parsed
#' column types. By default, extracts `path` and `user_agent` from the `data`
#' field, if available.
#'
#' @param x A `connect_list_hits` object (from [get_usage()]).
#' @param row.names Passed to [base::as.data.frame()].
#' @param optional Passed to [base::as.data.frame()].
#' @param ... Passed to [base::as.data.frame()].
#' @param unnest Logical; if `TRUE` (default), extracts nested fields using
#' \pkg{tidyr}. Set to `FALSE` to skip unnesting.
#'
#' @return A `data.frame` with one row per usage record.
#' @export
#' @method as.data.frame connect_list_hits
as.data.frame.connect_list_hits <- function(
x,
row.names = NULL, # nolint
optional = FALSE,
...,
unnest = TRUE
) {
usage_df <- parse_connectapi_typed(x, connectapi_ptypes$usage)
if (unnest) {
if (!requireNamespace("tidyr", quietly = TRUE)) {
stop(
"`unnest = TRUE` requires tidyr. Install tidyr or set `unnest = FALSE`.",
call. = FALSE
)
}
usage_df <- tidyr::unnest_wider(
usage_df,
"data",
ptype = list(path = character(0), user_agent = character(0))
)
}
as.data.frame(usage_df, row.names = row.names, optional = optional, ...)
}
#' Convert usage data to a tibble
#'
#' @description
#' Converts an object returned by [get_usage()] to a tibble via
#' [as.data.frame.connect_list_hits()].
#'
#' @param x A `connect_list_hits` object.
#' @param ... Passed to [as.data.frame()].
#'
#' @return A tibble with one row per usage record.
#' @export
#' @importFrom tibble as_tibble
#' @method as_tibble connect_list_hits
as_tibble.connect_list_hits <- function(x, ...) {
tibble::as_tibble(as.data.frame(x, ...))
}

Both this and #448 imply that the list returned should be an S3 class.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions