var_to_val_at_ids: #' Produce a summary of a dataframe in long format #' #'...

View source: R/write_functions.R

var_to_val_at_idsR Documentation

#' Produce a summary of a dataframe in long format #' #' @param df Dataframe #' @param id ID column in df #' #' @return Returns a dataframe with 5 columns: Variable var, val, #' n, ids & class. #' ids & showing all the values #' val (type indicated in class) each variable var of #' df takes. #' The list column ids (contains all the #' corresponding valus of id) and has n entries. #' @importFrom dplyr case_when #' @importFrom purrr transpose #' @export #' #' @examples #' df <- #' tibble::tibble( #' fbnr = 1:10, #' sex = haven::labelled(c(2, 1, 2, 1, 1, 2, 2, 1, 2, 1), #' label = "sex", #' labels = c(MALES = 1, FEMALES = 2)), #' age = c(24, 23, 23, 41, 23, 39, 30, 18, 31, 48), #' marital = haven::labelled( #' c(1, 7, 2, 6, 4, 5, 3, 8, 4, 2), #' label = "marital status", #' labels = c( #' "single" = 1, #' "steady relationship" = 2, #' "living with partner" = 3, #' "married first time" = 4, #' "remarried" = 5, #' "separated" = 6, #' "divorced" = 7, #' "non-occuring label" = 9 #' ) #' ) #' ) #' longen_id_sum(df, "fbnr")

Description

longen_id_sum <- function(df, id = "id") df %>% tab_cts(id, include_ids = TRUE) %>% left_join(df %>% unattr() %>% tab_attrs() %>% select(.data$var, .data$class)) %>% group_by(.data$class) %>% mutate(val = case_when(class == "numeric" ~ as.numeric(.data$val) %>% as.list(), class == "character" ~ .data$val %>% as.list())) Set variable of a dataframe to a value in the rows of a list of ids.

Usage

var_to_val_at_ids(df, l)

Arguments

df

Dataframe with an id column named "id".

l

list which must contain 3 elements: l$var the variable name, and l$ids a list of ids where the value l$val is to be assigned.

Value

Copy of df with the overwritten cells explained above

Examples

df <- data.frame(id = 1:10,
                 sex = c(2, 1, 2, 1, 1, 2, 2, 1, 2, 1),
                 age = c(24, 23, 23, 41, 23, 39, 30, 18, 31, 48))
# Produce data summary:
df_cts <- tab_cts(df, include_ids = TRUE)
# Take the id column of df and reassign the first row in df_cts:
df_copy <-
  var_to_val_at_ids(
    df["id"],
    df_cts[1,] %>%
      make_type_list() %>%
      purrr::transpose() %>%
      .[[1]]
   )
df_copy

urswilke/tablab documentation built on Oct. 17, 2022, 8:19 p.m.