content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' Recode survey items for use in Rasch Analysis
#'
#' @inheritParams rasch_mds
#' @inheritParams rasch_testlet
#'
#' @return a named list with:
#' \item{df}{new \code{df} after recoding the desired variables}
#' \item{max_values}{new \code{max_values} after recoding the desired variables}
#'
#' @family rasch functions
#' @family children analysis functions
#'
#' @export
#'
#' @import dplyr
rasch_recode <- function(df, vars_metric, recode_strategy, max_values) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#How many different kinds of recode?
n_recode <- length(recode_strategy)
#What is the recode outcome?
for (i in 1:n_recode) {
#capture desired recode outcome and variables to recode
new_outcome <- recode_strategy[[i]]
new_recoded <- names(recode_strategy)[i]
new_recoded <- unlist(strsplit(new_recoded,","))
if (!all(new_recoded %in% helper_varslist(vars_metric))) stop("You input a string that is not included in the variable list.")
#capture range of maximum values for each recoded variable and test if max values are equal
resp_opts_range <- max_values %>%
filter(var %in% new_recoded) %>%
pull("max_val") %>%
as.numeric() %>%
range()
if (!isTRUE(all.equal(resp_opts_range[1],resp_opts_range[2]))) stop("You input variables with different possible response options.")
if (length(new_outcome)!=unique(resp_opts_range)+1) stop("Outcome string must have same # of characters as possible response options.")
#edit data.frame of maximum possible values
max_values <- max_values %>%
mutate(max_val = ifelse(var %in% new_recoded, utils::tail(new_outcome,1), max_val))
#perform the recode
df <- df %>%
mutate_at(vars(new_recoded),
list(~ plyr::mapvalues(., from = 0:unique(resp_opts_range),
to = new_outcome,
warn_missing = FALSE)))
}
recode_result <- list(df = df,
max_values = max_values)
return(recode_result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_recode.R
|
#' Rescale score from Rasch Analysis to range from 0 to 100
#'
#' @param df_score a tibble resulting from \code{rasch_model()} with the person abilities from the Rasch Model
#' @inheritParams rasch_mds
#'
#' @return a tibble with the left join between \code{df} and \code{df_score} and new column "rescaled" with the rescaled person abilities, ranging from 0 to 100, and filter out any rows with an artificial minimum or maximum
#'
#' @family rasch functions
#'
#' @export
#'
#'
rasch_rescale <- function(df, df_score, vars_id) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
df_final <- df %>%
left_join(df_score) %>%
mutate(rescaled = scales::rescale(person_pars, c(0,100))) %>%
filter_at(vars(vars_id), any_vars(. != "MAX")) %>%
filter_at(vars(vars_id), any_vars(. !="MIN"))
return(df_final)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_rescale.R
|
#' Rescale score from Rasch Analysis for children to range from 0 to 100
#'
#' @inheritParams rasch_mds
#' @inheritParams rasch_mds_children
#' @inheritParams rasch_model_children
#'
#' @return a tibble with the data \code{df} or unnested \code{df_nest} and new columns "person_pars" and "rescaled" with the original and rescaled person abilities, ranging from 0 to 100, and filter out any rows with an artificial minimum or maximum
#'
#' @family rasch functions
#' @family children analysis functions
#'
#' @export
#'
rasch_rescale_children <- function(df, df_nest, vars_group, vars_id) {
#Anchored
if ("WLE_anchored" %in% names(df_nest)) {
df_final <- df_nest %>%
dplyr::mutate(df_split = purrr::map2(df_split, WLE_anchored, function(df_age, WLE_age) {
df_age <- df_age %>%
tibble::add_column(person_pars = WLE_age$theta) %>%
dplyr::select(-!!rlang::sym(vars_group))
return(df_age)
})) %>%
dplyr::select(all_of(c(vars_group, "df_split"))) %>%
tidyr::unnest(cols = c(df_split))
}
#Multigroup
else {
df_final <- df %>%
tibble::add_column(person_pars = df_nest$WLE_multigroup[[1]]$theta)
}
df_final <- df_final %>%
dplyr::mutate(rescaled = scales::rescale(person_pars, c(0, 100))) %>%
dplyr::filter_at(dplyr::vars(dplyr::all_of(vars_id)), dplyr::any_vars(. != "MAX")) %>%
dplyr::filter_at(dplyr::vars(dplyr::all_of(vars_id)), dplyr::any_vars(. !="MIN"))
return(df_final)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_rescale_children.R
|
#' Split survey items by categories for a Rasch Model
#'
#'
#' @inheritParams rasch_mds
#' @inheritParams rasch_testlet
#'
#' @details If significant differential item functioning (DIF) is observed, it may be desirable to split variables based on the characteristic for which DIF is observed. For example, if men and women have significantly different patterns of responses to items, then it may be desirable to split items by sex. This function performs that variable splitting.
#'
#' @return a named list with:
#' \item{df}{new \code{df} after splitting the desired variables}
#' \item{vars_metric}{new \code{vars_metric} after splitting the desired variables}
#' \item{max_values}{new \code{max_values} after splitting the desired variables}
#' @export
#'
#' @family rasch functions
#' @family children analysis functions
#'
#' @import dplyr
#' @import rlang
rasch_split <- function(df, vars_metric, split_strategy, max_values) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#How many different kinds of splitting?
n_split <- length(split_strategy)
for (i in 1:n_split) {
#capture new variable to split by
new_split_by <- names(split_strategy)[i]
if (!(new_split_by %in% names(df))) stop("You input a string to split by that is not included in the variable list.")
#categories of split variable
split_cats <- df %>% pull(new_split_by) %>% unique()
#capture variables to split
new_vars_to_split <- split_strategy[[i]]
if (!all(new_vars_to_split %in% helper_varslist(vars_metric))) stop("You input a string that is not included in the variable list.")
#create split
for (ct in split_cats) {
for (var in new_vars_to_split) {
df <- df %>%
mutate(!!rlang::sym(paste(var,ct, sep="_")) := case_when(
!!rlang::sym(new_split_by)==ct ~ !!rlang::sym(var)
))
}
}
#edit list of variables
if (is.list(vars_metric)) {
vars_metric <- purrr::map(vars_metric, function(vset) {
test <- vset %in% new_vars_to_split
if (any(test)) {
new_split_vars <- paste(rep(vset[which(test)],
each = length(split_cats)),
split_cats, sep = "_")
new_vset <- vset[-which(test)]
new_vset <- c(new_vset, new_split_vars)
} else new_vset <- vset
return(new_vset)
})} else {
new_split_vars <- paste(rep(new_vars_to_split,each=length(split_cats)),
split_cats,sep="_")
vars_metric <- vars_metric[-which(vars_metric %in% new_vars_to_split)]
vars_metric <- c(vars_metric, new_split_vars)
}
#edit max_values
new_max_values <- max_values %>%
slice(rep(which(var %in% new_vars_to_split),
each = length(split_cats))) %>%
mutate(var = paste(var, split_cats, sep="_"))
max_values <- max_values %>%
filter(!(var %in% new_vars_to_split)) %>%
bind_rows(new_max_values)
}
#save results
split_result <- list(df = df,
vars_metric = vars_metric,
max_values = max_values,
split_strategy = split_strategy)
return(split_result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_split.R
|
#' Split all survey items by age category for a Rasch Model if they are not discrete
#'
#' @inheritParams rasch_mds_children
#' @inheritParams rasch_mds
#' @inheritParams rasch_testlet
#'
#' @return a named list with:
#' \item{df}{new \code{df} after splitting the variables}
#' \item{vars_metric}{new \code{vars_metric} after splitting the variables}
#' \item{max_values}{new \code{max_values} after splitting the variables}
#' @export
#'
#' @family rasch functions
#' @family children analysis functions
#'
rasch_split_age <- function (df, vars_group, vars_metric, vars_id, max_values) {
#capture levels of age_group
levels_age_group <- levels(pull(df, vars_group))
#initialize list of overlapping varibles
vars_metric_overlap <- vector("list",length(vars_metric))
names(vars_metric_overlap) <- names(vars_metric)
#create list of overlapping variables for each age group and vector of all variables
for (i in seq_along(vars_metric)) {
vars_metric_overlap[[i]] <- vars_metric[[i]][vars_metric[[i]] %in% unlist(vars_metric[-i])]
}
vars_metric_overlap_all <- helper_varslist(vars_metric_overlap)
#if there are overlapping variables, make the split
if (length(vars_metric_overlap_all) != 0) {
#initialize list to store pivot data with new discrete variables by age group
df_split <- vector("list", length(vars_metric_overlap_all))
names(df_split) <- vars_metric_overlap_all
#for each variable that overlaps over multiple age groups
for (var in vars_metric_overlap_all) {
#select vars needed
subtbl <- df %>%
select(vars_id, vars_group, var)
#pivot variables to create three discrete variables
subtbl_pivot <- subtbl %>%
tidyr::pivot_wider(names_from = !!quo(vars_group), values_from = !!quo(var)) %>%
rename_at(vars(levels_age_group), list(~ paste0(var,"_",.)))
#give error if number of rows isn't maintained
if (nrow(subtbl_pivot) != nrow(df)) stop(paste0("Pivoted table for ", var, " has nrow that doesn't match nrow(df). Check what's going on."))
#save pivot data in list
df_split[[var]] <- subtbl_pivot
}
#combine new vars with rest of the data
df <- df_split %>%
purrr::reduce(left_join) %>%
left_join(df)
#edit list of variables - all list and grouped list
vars_metric_almost <- purrr::map(names(vars_metric), function(nm_vset) {
vset <- vars_metric[[nm_vset]]
test <- vset %in% vars_metric_overlap_all
if (any(test)) {
new_split_vars <- paste0(vset[which(test)], "_",
nm_vset)
new_vset <- vset[-which(test)]
new_vset <- c(new_vset, new_split_vars)
} else {
new_vset <- vset
}
return(new_vset)
})
names(vars_metric_almost) <- names(vars_metric)
#edit max values
max_values_almost <- purrr::map(names(vars_metric), function(nm_vset) {
vset <- vars_metric[[nm_vset]]
test <- vset %in% vars_metric_overlap_all
if (any(test)) {
new_max_values <- max_values %>%
filter(var %in% vset[which(test)]) %>%
mutate(var = paste0(var, "_", nm_vset))
return(new_max_values)
}
})
#finish up edits
vars_metric <- vars_metric_almost
max_values <- max_values %>%
filter(!(var %in% vars_metric_overlap_all)) %>%
bind_rows(max_values_almost)
}
split_age_result <- list(df = df,
vars_metric = vars_metric,
max_values = max_values)
return(split_age_result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_split_age.R
|
#' Create testlets of survey items for a Rasch Model
#'
#' @param max_values a tibble with two columns, \code{var} equivalent to \code{vars_metric} and \code{max_val} with their corresponding maximum possible values
#' @inheritParams rasch_mds
#'
#' @details If high local item dependence is observed (i.e., residual correlation) is observed between items, it may be desirable to combine them into a testlet. This code creates the testlets as desired.
#'
#' @return a named list with:
#' \item{df}{new \code{df} after creating desired testlets}
#' \item{vars_metric}{new \code{vars_metric} after creating desired testlets}
#' \item{testlet_strategy}{new \code{testlet_strategy} after creating desired testlets}
#' \item{max_values}{new \code{max_values} after creating desired testlets}
#'
#' @export
#'
#' @family rasch functions
#' @family children analysis functions
#'
#' @import dplyr
rasch_testlet <- function(df, vars_metric, testlet_strategy, max_values, resp_opts) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
n_testlets <- length(testlet_strategy)
#for each testlet
for (i in 1:n_testlets) {
#capture variables for new testlet
new_testlet_vars <- testlet_strategy[[i]]
new_testlet_name <- names(testlet_strategy)[i]
if (!all(new_testlet_vars %in% helper_varslist(vars_metric))) stop("You input a string that is not included in the variable list.")
#create testlet
if (!is.null(new_testlet_name) & !identical(new_testlet_name,"") & !identical(new_testlet_name,NA_character_)) {
new_testlet <- new_testlet_name
} else {
new_testlet <- paste(new_testlet_vars,collapse="_")
names(testlet_strategy)[i] <- new_testlet
}
df <- df %>%
mutate(!!rlang::sym(new_testlet) := rowSums(df[,new_testlet_vars],na.rm=TRUE))
#edit list of variables
if (is.list(vars_metric)) {
vars_metric <- purrr::map(vars_metric, function(vset) {
if (all(new_testlet_vars %in% vset)) {
new_vset <- vset[-which(vset %in% new_testlet_vars)]
new_vset <- c(new_vset, new_testlet)
} else {
new_vset <- vset
}
return(new_vset)
})
} else {
vars_metric <- vars_metric[-which(vars_metric %in% new_testlet_vars)]
vars_metric <- c(vars_metric,new_testlet)
}
#edit data.frame of maximum possible values
max_values <- max_values %>% filter(!(var %in% new_testlet_vars))
max_values <- max_values %>% bind_rows(tibble(var = new_testlet,
max_val = (max(resp_opts)-1)*length(new_testlet_vars)))
}
testlet_result <- list(df = df,
vars_metric = vars_metric,
testlet_strategy = testlet_strategy,
max_values = max_values)
return(testlet_result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_testlet.R
|
#' Compute basic statistics of the number of members per group per household
#'
#' @param df a data frame of household data where the rows represent members of the households in the sample
#' @param hh_id string (length 1) indicating the name of the variable in \code{df} uniquely identifying households
#' @param group_by_var string (length 1) to pass to \code{group_by_at()} with name of variable in \code{df} to group results by
#'
#' @return A tibble with rows for each level of \code{group_by_var} and "Total" and columns for the Mean (SD), Median and Range of the number of people in each group per household.
#'
#' @note Includes a call to \code{tidyr::complete()}, which causes the function to be a bit slow.
#'
#' @export
#'
#' @family table functions
#'
#' @import dplyr
#' @import rlang
#'
#' @examples
#' #create dummy table of household data, where each row represents one member
#' df_hh <- data.frame(HHID = sample(
#' x = 1:300,
#' size = 1000,
#' replace = TRUE
#' ),
#' age_cat = ordered(sample(
#' x = c("18-24", "25-39", "40-64", "64-100"),
#' size = 1000,
#' replace = TRUE
#' )))
#'
#' table_basicstats(df_hh, "HHID", "age_cat")
table_basicstats <- function(df, hh_id, group_by_var) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
sym_group_by_var <- sym(group_by_var)
disaggregated <- df %>%
group_by_at(c(hh_id, group_by_var)) %>%
summarize(nperHH = n()) %>%
tidyr::complete(!!sym_group_by_var, fill = list(nperHH=0)) %>%
group_by_at(c(group_by_var)) %>%
summarize(mean = round(mean(nperHH), 1),
sd = round(stats::sd(nperHH), 1),
median = round(stats::median(nperHH), 1),
min = round(min(nperHH), 1),
max = round(max(nperHH), 1)) %>%
transmute(!!sym_group_by_var,
mean_sd = paste0(mean," (", sd, ")"),
median,
range = paste0(min, " - ", max))
total <- df %>%
group_by_at(c(hh_id)) %>%
summarize(nperHH = n()) %>%
summarize(mean = round(mean(nperHH),1),
sd=round(stats::sd(nperHH),1),
median = round(stats::median(nperHH),1),
min=round(min(nperHH),1),
max=round(max(nperHH),1)) %>%
transmute(mean_sd = paste0(mean," (", sd, ")"),
median,
range = paste0(min, " - ", max)) %>%
tibble::add_column(!!sym_group_by_var := "Total", .before=1)
tab <- bind_rows(disaggregated,total)
return(tab)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/table_basicstats.R
|
#' Compute unweighted percent and N for multiple variables, disaggregated
#'
#' @param vars_demo a character vector of names of variables to calculate percent and N for
#' @param group_by_var a string (length 1) with the name of the variable from \code{df} to disaggregate by
#' @param spread_by_group_by_var logical determining whether to pass \code{group_by_var} to \code{tidyr::pivot_wider()} to give a wide-format tab. Default is FALSE.
#' @param group_by_var_sums_to_100 logical determining whether percentages sum to 100 along the margin of \code{group_by_var}, if applicable. Default is FALSE.
#' @param add_totals logical determining whether to create total rows or columns (as appropriate) that demonstrate the margin that sums to 100. Default is FALSE.
#' @inheritParams rasch_mds
#'
#' @return A tibble with percent and N for each level of each variable in \code{vars_demo}
#'
#' @family table functions
#'
#' @export
#'
#' @import dplyr
#' @import rlang
#' @import tidyr
#'
#' @examples
#' table_unweightedpctn(df_adults, vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"))
#' table_unweightedpctn(df_adults, vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"),
#' group_by_var = "disability_cat")
#' table_unweightedpctn(df_adults, vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"),
#' group_by_var = "disability_cat", spread_by_group_by_var = TRUE)
table_unweightedpctn <- function(df, vars_demo,
group_by_var=NULL,
spread_by_group_by_var = FALSE,
group_by_var_sums_to_100 = FALSE,
add_totals = FALSE) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#create sym of group_by_var if applicable
if (!is.null(group_by_var)) {
sym_group_by_var <- sym(group_by_var)
#initialize final table
final_tab <- tibble(
item = character(),
demo = character(),
!!sym_group_by_var := character(),
n = numeric(),
pct = numeric()
)
} else {
final_tab <- tibble(
item = character(),
demo = character(),
n = numeric(),
pct = numeric())
}
#for each vars_demo...
for (i in seq_along(vars_demo)){
#create sym of vars_demo at this iteration
sym_this_vars_demo <- sym(vars_demo[i])
#remove NAs of this vars_demo
tab <- df %>%
filter(!is.na(!!sym_this_vars_demo))
#if grouping, remove NAs of group_by_var
if (!is.null(group_by_var)) {
tab <- tab %>%
filter(!is.na(!!sym_group_by_var))
}
#start grouping
if (group_by_var_sums_to_100) {
tab <- tab %>%
group_by_at(c(vars_demo[i], group_by_var))
}
if (!group_by_var_sums_to_100) {
tab <- tab %>%
group_by_at(c(group_by_var, vars_demo[i]))
}
#create summary table
tab <- tab %>%
summarize(n=n()) %>%
mutate(pct=round(n/sum(n)*100,1)) %>%
rename(demo = !!sym_this_vars_demo) %>%
tibble::add_column(item = vars_demo[i], .before = 1)
final_tab <- bind_rows(final_tab, tab)
}
if (!is.null(group_by_var)) {
final_tab <- final_tab %>%
mutate(demo = ordered(demo, levels = unique(demo)),
!!sym_group_by_var := ordered(!!sym_group_by_var, levels=unique(!!sym_group_by_var))) %>%
select(item, demo, !!sym_group_by_var, pct, n)
#pivot, if applicable
if (spread_by_group_by_var) {
final_tab <- final_tab %>%
transmute(item, demo, !!sym_group_by_var,
pct_n = paste0(pct, "_", n)) %>%
tidyr::pivot_wider(names_from = !!sym_group_by_var, values_from = pct_n)
#separate pct and n
for (col in colnames(final_tab)[-(1:2)]) {
final_tab <- final_tab %>%
tidyr::separate(!!rlang::sym(col),
into = paste0(col, "_", c("pct", "n")),
sep = "_")
}
}
} else {
final_tab <- final_tab %>%
mutate(demo = ordered(demo, levels = unique(demo))) %>%
select(item, demo, pct, n)
}
#make sure appropriate columns are numeric
if ((!is.null(group_by_var)) & !spread_by_group_by_var) {
final_tab <- final_tab %>%
mutate_at(vars(-item, -demo, -!!sym(group_by_var)), as.numeric)
} else {
final_tab <- final_tab %>%
mutate_at(vars(-item, -demo), as.numeric)
}
if (!is.null(group_by_var) & spread_by_group_by_var) {
final_tab <- final_tab %>%
arrange(match(item, vars_demo))
}
#add totals, if applicable
if (add_totals) {
#if grouping...
if (!is.null(group_by_var)) {
#if pivoting...
if (spread_by_group_by_var) {
#if summing along group_by_var... (total col)
if (group_by_var_sums_to_100) {
# table_unweightedpctn(df_adults, vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"), add_totals = TRUE, group_by_var = "disability_cat", spread_by_group_by_var = TRUE, group_by_var_sums_to_100 = FALSE)
final_tab <- final_tab %>%
tibble::add_column(Total_pct = (final_tab %>%
select(ends_with("_pct")) %>%
rowSums(na.rm = TRUE)),
Total_n = (final_tab %>%
select(ends_with("_n")) %>%
rowSums(na.rm = TRUE)))
}
#if not summing along group_by_var... (total row)
else {
# table_unweightedpctn(df_adults, vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"), add_totals = TRUE, group_by_var = "disability_cat", spread_by_group_by_var = TRUE, group_by_var_sums_to_100 = TRUE)
final_tab <- final_tab %>%
mutate(item = ordered(item)) %>%
split(.$item) %>%
purrr::map_dfr(function(df) {
df %>%
bind_rows(
df %>%
summarize_at(vars(-item, -demo), list(~ sum(., na.rm = TRUE))) %>%
tibble::add_column(item = unique(df$item), demo = "Total", .before = 1)
)
})
}
final_tab <- final_tab %>%
arrange(match(item, vars_demo))
}
#if not spreading...
else {
#if summing along group_by_var...
if (group_by_var_sums_to_100) {
# table_unweightedpctn(df_adults, vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"), add_totals = TRUE, group_by_var = "disability_cat", spread_by_group_by_var = FALSE, group_by_var_sums_to_100 = TRUE)
final_tab <- final_tab %>%
group_by(item, !!sym(group_by_var)) %>%
nest() %>%
mutate(data = purrr::map(data, function(df) {
df %>%
add_row(demo = "Total", pct = sum(df$pct, na.rm = TRUE), n = sum(df$n, na.rm = TRUE))
})) %>%
unnest(cols = data)
}
#if not summing along group_by_var...
else {
# table_unweightedpctn(df_adults, vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"), add_totals = TRUE, group_by_var = "disability_cat", spread_by_group_by_var = FALSE, group_by_var_sums_to_100 = FALSE)
final_tab <- final_tab %>%
group_by(item, demo) %>%
nest() %>%
mutate(data = purrr::map(data, function(df) {
df %>%
add_row(!!sym(group_by_var) := "Total", pct = sum(df$pct, na.rm = TRUE), n = sum(df$n, na.rm = TRUE))
})) %>%
unnest(cols = data)
}
}
}
#if not grouping...
else {
# table_unweightedpctn(df_adults, vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"), add_totals = TRUE, group_by_var = NULL)
final_tab <- final_tab %>%
group_by(item) %>%
nest() %>%
mutate(data = purrr::map(data, function(df) {
df %>%
add_row(demo := "Total", pct = sum(df$pct, na.rm = TRUE), n = sum(df$n, na.rm = TRUE))
})) %>%
unnest(cols = data)
}
}
return(final_tab)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/table_unweightedpctn.R
|
#' Calculate table of percentages or N of response distribution for survey items, survey weighted, disaggregated
#'
#' @param vars_ids a character vector of cluster ids, passed to \code{srvyr::as_survey_design()}
#' @param vars_strata a character vector of strata ids, passed to \code{srvyr::as_survey_design()}
#' @param vars_weights a character vector of survey weight ids, passed to \code{srvyr::as_survey_design()}
#' @param formula_vars a character vector of variables to calculate the percentages of each level for
#' @param ... captures expressions to pass to \code{dplyr::filter()} or \code{dplyr::transmute()}, depending on the value of argument \code{willfilter}. See Details.
#' @param formula_vars_levels a vector of the levels of the the \code{formula_vars}
#' @param by_vars a character vector of variables to disaggregate results by. Default is \code{NULL} for no disaggregation. The columns listed must not include NAs.
#' @param pct a logical variable indicating whether or not to calculate weighted percentages. Default is \code{TRUE} for weighted percentages. Set to \code{FALSE} for weighted N.
#' @param willfilter a logical variable that tells the function whether or not to filter or transmute the data. Leave as default \code{NULL} to not filter or transmute. Set as \code{TRUE} to filter and \code{FALSE} to transmute. See Details.
#' @param spread_key a string with variable name to pass to \code{names_from} argument of \code{tidyr::pivot_wider()}. Default is \code{NULL}.
#' @param spread_value a string with variable name to pass to \code{values_from} argument of \code{tidyr::pivot_wider()}. Default is "prop" (the column of percentages created within the function)
#' @param arrange_vars a character vector with variables to pass to \code{dplyr::arrange()}. Default is NULL.
#' @param include_SE a logical variable indicating whether to include the standard errors in the table. Default is FALSE. Currently does not work when adding totals, spreading or transmuting.
#' @inheritParams rasch_mds
#' @inheritParams table_unweightedpctn
#'
#' @return a tibble of weighted response percentages or N's
#'
#' @details
#' If \code{willfilter} is NULL, the table is not filtered or transmuted. If \code{willfilter} is TRUE, the table is filtered before it is spread or arranged. If \code{willfilter} is FALSE, the table is transmuted after the spread and/or arrange. "..." captures the non-standard evaluation expressions (NSE) to pass to \code{dplyr::filter} or \code{dplyr::transmute()}.
#'
#' The function performs the following actions with the table after results are calculated in the following order (if applicable): filter, add totals, spread, arrange, transmute
#'
#' @family table functions
#'
#' @export
#'
#' @import srvyr
#'
#' @seealso See \code{vignette("programming", package = "dplyr")} for more about non-standard evaluation (NSE)
#'
#' @examples
#' table_weightedpct(df_adults,
#' vars_ids = c("HHID", "PSU"),
#' vars_strata = "strata",
#' vars_weights = "weight",
#' formula_vars = paste0("EF",1:10),
#' formula_vars_levels = 1:5,
#' by_vars = "sex")
table_weightedpct <- function(df, vars_ids, vars_strata, vars_weights,
formula_vars, ...,
formula_vars_levels = 0:1, by_vars = NULL,
pct = TRUE,
willfilter = NULL,
add_totals = FALSE,
spread_key = NULL, spread_value = "prop",
arrange_vars = NULL,
include_SE = FALSE
) {
##TESTING: if include_SE = TRUE, don't allow for adding totals, spreading, filtering, transmuting
if (include_SE) {
if(add_totals) stop("For testing of include_SE, add_totals must be FALSE")
if(isFALSE(willfilter)) stop("For testing of include_SE, willfilter must be NULL or TRUE (i.e., must not transmute in order to avoid SE's from being erroneously summed)")
if(!is.null(spread_key)) stop("For testing of include_SE, spread_key must be NULL")
}
#check for NAs in by_vars
if (!is.null(by_vars)) {
any_NAs <- df %>%
select(!!by_vars) %>%
filter_all(is.na) %>%
nrow() %>%
`>`(., 0)
} else any_NAs <- FALSE
if(any_NAs) stop("Remove NAs from by_vars columns first.")
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#convert data to long format using variables from formula_vars
df <- df %>%
tidyr::pivot_longer(
c(!!!rlang::syms(formula_vars)),
names_to = "item",
values_to = "resp",
values_drop_na = TRUE
) %>%
# mutate(resp = ordered(resp, levels = formula_vars_levels),
mutate(resp = factor(resp, levels = formula_vars_levels),
item = ordered(item))
#warning if lonely psu option is not set correctly
if (getOption("survey.lonely.psu")!="adjust") warning('You may have issues with lonely PSUs if you have not set: options(survey.lonely.psu = "adjust")')
#create survey design object
if (is.null(vars_ids)) expr_ids <- "NULL" else expr_ids <- paste0("c(", paste0(vars_ids, collapse = ","), ")")
if (is.null(vars_strata)) expr_strata <- "NULL" else expr_strata <- paste0("c(", paste0(vars_strata, collapse = ","), ")")
if (is.null(vars_weights)) expr_weights <- "NULL" else expr_weights <- paste0("c(", paste0(vars_weights, collapse = ","), ")")
des <-
df %>%
as_survey_design(
ids = !!rlang::parse_expr(expr_ids),
strata = !!rlang::parse_expr(expr_strata),
weights = !!rlang::parse_expr(expr_weights),
nest = TRUE
)
#store ... expressions for filter() or transmute()
if (!is.null(willfilter)) {
exprs <- quos(...)
if (length(exprs)==0) stop("willfilter is not NULL but you didn't include any expressions to pass to filter() or transmute()")
}
#initialize results table
#if wanting weighted percentage
if (pct) {
prevtab <- des %>%
group_by_at(c(by_vars, "item", "resp")) %>%
summarize(prop = survey_mean(na.rm=TRUE)) %>%
mutate(prop = prop*100)
if (include_SE) {
prevtab <- prevtab %>%
mutate(prop_se = prop_se*100)
} else {
prevtab <- prevtab %>%
dplyr::select(-prop_se)
}
} else { #if wanting weighted N
prevtab <- des %>%
group_by_at(c(by_vars, "item", "resp")) %>%
summarize(total = survey_total(na.rm=TRUE))
if (!include_SE) {
prevtab <- prevtab %>%
dplyr::select(-total_se)
}
}
#filter, if willfilter==TRUE
if (!is.null(willfilter) & isTRUE(willfilter)) prevtab <- prevtab %>% filter(!!!exprs)
#add totals, if applicable
if (add_totals) {
prevtab <- prevtab %>%
group_by_at(c(by_vars, "item")) %>%
tidyr::nest() %>%
mutate(data = purrr::map(data, function(df) {
df %>%
add_row(resp := "Total", prop = sum(df$prop, na.rm = TRUE))
})) %>%
tidyr::unnest(cols = c(data))
}
#spread
if (!is.null(spread_key)) {
prevtab <- prevtab %>%
tidyr::pivot_wider(names_from = !!rlang::sym(spread_key), values_from = !!rlang::sym(spread_value))
}
#arrange
if (!is.null(arrange_vars)) {
prevtab <- prevtab %>%
arrange_at(arrange_vars)
}
#transmute, if willfilter==FALSE (collapse response options) - (if spread_key is disability_cat, then can't use transmute here to collapse response options)
if (!is.null(willfilter) & !isTRUE(willfilter)) prevtab <- prevtab %>% transmute(!!!exprs)
return(prevtab)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/table_weightedpct.R
|
#' whomds: A package for calculating results from WHO Model Disability Survey
#'
#' The whomds package provides three categories of important functions:
#' table functions, figure functions, and Rasch Analysis functions
#'
#' @section Table functions:
#' The table functions output different fit for purpose tables for reporting
#' results from the WHO Model Disability Survey (MDS). They begin with \code{table_*()}
#'
#' @section Figure functions:
#' The figures functions output different figures for reporting
#' results from the WHO Model Disability Survey (MDS). They begin with \code{fig_*()}
#'
#' @section Rasch Analysis functions:
#' These functions are used to complete an iteration of Rasch Analysis for WHO Model Disability Survey (MDS). They begin with \code{rasch_*}
#'
#'
#' @references WHO Model Disability Survey: \url{https://www.who.int/health-topics/disability}
#' @keywords internal
"_PACKAGE"
#quiets R CMD check
if (getRversion() >= "2.15.1") {
utils::globalVariables(
c(
".",
"age_cat",
"anchored_xsi",
"cor_anchored",
"cor_multigroup",
"cor_start",
"data",
"demo",
"df_split",
"df_split_selected",
"disordered",
"fit",
"index_uniqueitems",
"item",
"layout.kamada.kawai",
"max_val",
"median",
"Metric",
"mod_anchored",
"mod_multigroup",
"mod_start",
"model_results",
"multigroup_xsi",
"n_threshold",
"name",
"nodes",
"nperHH",
"original",
"original_var",
"pct",
"pct_n",
"person",
"person_pars",
"prop",
"prop_se",
"Q",
"RawScore",
"recoded",
"resp",
"sd",
"SE Threshold",
"sex",
"split_category",
"start_xsi",
"Threshold",
"total_se",
"var",
"var1",
"var2",
"Var1",
"variable",
"variable_to_split",
"vars_id",
"vert_clr",
"WLE_anchored"
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/whomds-package.R
|
.onAttach <- function(libname, pkgname) {
packageStartupMessage("Thank you for using whomds. To learn more about the WHO Model Disability Survey (MDS) and for contact information, go to https://www.who.int/health-topics/disability")
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/zzz.R
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(whomds)
options(survey.lonely.psu = "adjust")
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
## ----plot-scales, eval=TRUE, echo=FALSE---------------------------------------
include_graphics("Images/scales.png")
## ----plot-ruler, eval=TRUE, echo=FALSE----------------------------------------
include_graphics("Images/ruler.png")
## ----plot-oranges, eval=TRUE, echo=FALSE--------------------------------------
include_graphics("Images/oranges.png")
## ----plot-distributionruler, eval=TRUE, echo=FALSE----------------------------
include_graphics("Images/distributionruler.png")
## ----plot-continuum, eval=TRUE, echo=FALSE------------------------------------
include_graphics("Images/continuum.png")
## ----plot-continuum-person, eval=TRUE, echo=FALSE-----------------------------
include_graphics("Images/continuum_person.png")
## ----plot-continuum-personitem, eval=TRUE, echo=FALSE-------------------------
include_graphics("Images/continuum_personitem.png")
## ----rasch-setup, echo=FALSE, eval=TRUE, out.width = NULL---------------------
x <- seq(-5,5,0.01)
y <- exp(x)/(1+exp(x))
df <- tibble(x,y)
ggplot(df,aes(x=x,y=y)) +
geom_point() +
labs(x="Difference between person ability\n and item difficulty", y="Probability of person getting\n question correct")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
## ----rasch-setup-poly, echo=FALSE, eval=TRUE, out.width = NULL----------------
x <- seq(-5,5,0.01)
tao <- c(-2.5,0,2.5)
y0 <- exp(x-tao[1])/(1+exp(x-tao[1]))
y1 <- exp(x-tao[2])/(1+exp(x-tao[2]))
y2 <- exp(x-tao[3])/(1+exp(x-tao[3]))
df <- tibble(x,y0,y1,y2)
df.long <- df %>%
pivot_longer(!x, names_to = "Threshold", values_to = "y")
ggplot(df.long,aes(x=x,y=y,color=Threshold)) +
geom_point()+
scale_color_discrete(labels=c("First","Second","Third")) +
labs(x="Difference between person ability\n and item difficulty", y="Conditional probability of person\n passing response threshold")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
## ----iteration, echo=FALSE, eval=TRUE-----------------------------------------
include_graphics("Images/iteration_EN.png")
## ----plot-highjump, eval=TRUE, echo=FALSE-------------------------------------
include_graphics("Images/highjump.jpg")
## ----plot-repair, eval=TRUE, echo=FALSE---------------------------------------
include_graphics("Images/repair.png")
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c1_background_EN.R
|
---
title: "1 - Background on disability measurement"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{1 - Background on disability measurement}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(whomds)
options(survey.lonely.psu = "adjust")
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Introduction
## Background
In light of calls for sound and comprehensive disability data the Model Disability Survey (MDS) project was initiated by WHO and the World Bank (WB) in 2011.
The MDS is grounded in the International Classification of Functioning, Disability and Health (ICF) and represents an evolution in the concept of disability measurement. It explores disability as the experience of a person with a health condition or impairment encountering a facilitating or hindering environment, instead of solely focusing on the individual's health status.
In keeping with the conceptual framework of the ICF, the MDS takes the approach that:
* Disability is not an internal attribute of a person but an experience;
* Disability is etiologically neutral;
* Disability is a continuum, a quantity, and a matter of degree, ranging from no disability to extreme disability;
* Disability is universal, meaning every person sits somewhere on the disability continuum.
The rationale behind the MDS requires therefore a general population sample and the use of no filters, i.e. no _a priori_ selection of respondents, with three main goals:
* Achieving comparable and standardized disability prevalence rates across countries;
* Delivering the needed data for designing appropriate interventions, programs and policies for persons with mild, moderate and severe levels of disability;
* Monitoring the implementation of the Sustainable Development Goals (SDGs) and the United Nation Convention on the Rights of Persons with Disabilities (CRPD) by allowing for a direct comparison among persons with mild, moderate and severe levels of disability, and persons with no disability.
The MDS takes the approach that disability is a universal phenomenon characterized by a continuum ranging from low to high disability levels. This conceptualization requires information on disability to be reported and analyzed using metrical scales. This scale will range from 0 (no disability) to 100 (extreme disability).
Following an approach similar to the one of the World Report on Disability (WRD) and using modern test theory, functioning questions of Module 4000 are used to build a disability scale with metric properties. The whole general population sample is used to create this metric, which is then linearly transformed to range from 0 (lowest level of disability) to 100 (highest level).
## Purpose of this guide
The WHO Disability Programme offers technical support to countries to guide successful implementation of the survey and to analyze the resulting data. This guide is part of this package of technical support.
To create the disability scale, on which every individual in the same has a score from 0 to 100, WHO uses a technique called Rasch Analysis. The purpose of this guide is to explain in detail how Rasch Analysis is done and how to use the WHO package of codes, written in the statistical programming language `R`, in order to carry out the Rasch Analysis for the MDS.
## Objectives
1. Understand measurement and the information that different kinds of scales can provide;
2. Describe the reasoning and process behind Rasch Analysis;
3. Learn how to prepare data for a Rasch model;
4. Learn how to run a Rasch model;
5. Learn how to assess the quality of the Rasch model;
6. Learn how to adjust data to improve the quality of a Rasch model;
7. Understand how to use the package to calculate descriptive statistics.
# What is measurement?
At first glance, measurement seems very straight forward. However, the concept of "measurement" is actually made up of a few smaller components. It is important to understand each of these components when formulating any new measurement tool, like we are doing with the Model Disability Survey.
The main ideas of measurement are as follows:
* **Objects** have **properties** that can be thought in terms of more or less, larger or smaller, stronger or weaker.
* This **property** can be measured through its **manifestation** (or observable behavior).
* This **manifestation** can be mapped onto a **scale**.
* **Measurement** can have some **error** involved, and may not be perfectly precise.
For example, a person (**object**) has a certain intelligence regarding mathematics (**property**). This person's mathematical intelligence can be observed via their performance on a math test (**manifestation**). Their performance on the math test is given a score from 0 to 100 (**scale**). The score someone receives on a particular day can be influenced by random factors like their mood or the conditions of the room, so the score may not exactly reflect the person's true intelligence (**error**).
Just as there are different types of **properties** that objects can have (for example: height, weight, color, intelligence), there are also different types of **scales** that these properties can be measured with. Each of these different types of scales can give you different types of information, and you can only perform certain types of mathematical operations with each type of scale.
The four main types of scales are:
* **Nominal scale** - This scale involves assigning names to objects. For example, on a survey we often identify people as "Male" or "Female". This would be considered a nominal scale. The only mathematical operation available for this scale is assessment of equality. In other words, with nominal scales, you can only determine if two objects are the same or they are not.
* **Ordinal scale** - This scale involves placing objects in a particular order. For example, on a survey you often have questions with response options as follows: "Disagree strongly", "Disagree", "Neither agree nor disagree", "Agree", and "Agree strongly". This would be an ordinal scale. There are two mathematical operations possible with ordinal scales: equality and more/less. For example, with this scale you can determine if two objects give equal responses (for example, two people both answer "agree" to a question on a survey) or if one person's answer is "greater" than another's. For example, if Person A answers "agree" and Person B answers "agree strongly", you can be certain that Person B agrees more to the item than Person A. However, you cannot determine the "distance" between items. In other words, taking our example, you do not know _how much more_ Person B agrees than Person A.
* **Interval scale** - This scale involves placing objects at positions that have meaningful order and distance relative to other objects. For example, the weather on two days can have two different temperatures. Let's say Day 1 has a temperature of 10 degrees Celsius and Day 2 has a temperature of 20 degrees Celsius. This is an example of an interval scale. With this scale, we can use three different mathematical operations: we can determine if two objects are equal, if one is greater than another, and also the relative distance between them. In our example, clearly Day 1 and Day 2 have two different temperatures, and Day 2 is hotter than Day 1. But even more than that, we can say that Day 2 is exactly 10 degrees Celsius hotter than Day 1. Unlike with an ordinal scale, the distance between two points on the scale is meaningful. However, we cannot determine ratios between two points on the scale. In our example, we cannot say that Day 2 was twice as hot as Day 1. This is because 0 degrees Celsius is arbitrarily placed. When it is 0 degrees outside, it is cold, but there still is a temperature present.
* **Ratio scale** - This scale is like an interval scale, except that it also has a meaningful "0" point. We can apply four different mathematical operations to this scale: the three from an interval scale in addition to multiplication/division. For example, imagine Person A is 100cm tall and Person B is 150cm tall. Clearly we can determine that Person A is not the same height as Person B, Person A is shorter than Person B, and Person A is 50cm shorter than Person B. But even more than that, because 0cm is meaningful, we can say that Person B is 50% taller than Person A. We can create a ratio between their heights. Unlike with temperature, we can say for certain where 0cm is--if something is 0cm tall, then it's not there!
The table below gives a summary of what kind of information is possible with each scale.
```{r plot-scales, eval=TRUE, echo=FALSE}
include_graphics("Images/scales.png")
```
Most of the questions of the MDS are on a 5-point ordinal scale (for example, 1=None, 2=Some, 3=Moderate, 4=A lot, 5=Complete). In order to create a score we can use and trust, what we want to do is **take our ordinal data and map it onto an interval scale** of disability. In other words, using the ruler below as a reference, we want to move from the top of the ruler to the bottom.
```{r plot-ruler, eval=TRUE, echo=FALSE}
include_graphics("Images/ruler.png")
```
Why is simply adding up ordinal data not good enough? Imagine you are the CEO of a company that sells orange juice. You ask your employees, how much orange juice will we be able to produce this quarter? Employee A replies that the company has produced **5000 oranges** while Employee B replies that the company has produced **1500kg of oranges**. Who gave you the most information about how much orange juice you will be able to produce?
Employee B gave you information on an interval scale (weight), and Employee A gave you information on an ordinal scale (count). Employee B gave you more information; with her answer you know precisely how much orange juice you have to sell. Employee A told you how many oranges you have, but you have no idea how big or small they are.
```{r plot-oranges, eval=TRUE, echo=FALSE}
include_graphics("Images/oranges.png")
```
This scenario is similar to our questionnaire. We could just simply add up all answers to all the questions we are interested in to calculate a sum score. However, that sum score doesn't tell us much about the overall level of disability a person experiences, because we don't know which questions were identified as difficult, and different questions have different levels of difficulty.
For example, imagine that a person is answering questions from the Model Disability Survey. This person answered "3=Some problems" to both questions, "How much of a problem is toileting?" and "How much of a problem do you have with sleep?". One can imagine that difficulties with sleep are fairly common, and many of us experience problems with sleep without it impacting our lives too much. However, many fewer people have "some problems" with using the toilet, and one can imagine that having even some level of difficulty with using the toilet can cause significant problems in someone's life. Therefore, one can see that the answer of "3" to "sleep" is not equivalent to the "3" answered to "toileting".
So, in essence, we are trying to move from counting responses to questions about disability to truly measuring levels of disability on an interval scale. We will do this using **Rasch Analysis**.
# How does an interval scale apply to measuring disability?
Before we begin discussion of the technique of Rasch Analysis, it is important to emphasize again WHO's understanding of disability. We are measuring disability on an **interval scale**. This scale ranges from 0 (no disability) to 100 (extreme disability), and every person in the population sits somewhere on the scale.
This is quite different from the traditional way of thinking about disability. Often, when people hear the word "disability" they think of different "types of disabilities", and the people that most quickly come to mind are, for instance, people who are blind, people who are deaf, or people who use wheelchairs. For WHO, the word "disability" does not refer to attributes of specific, narrow groups of people who have particular impairments. For WHO, "disability" refers to a universal experience--not an attribute of a person--which is the outcome of a multitude of factors, like an underlying health condition or the accessibility of an environment.
As an example, take one person who has a vision impairment due to glaucoma and another person who has a mobility impairment due to a spinal cord injury. Both people may have difficulty using the transportation system. The person with a vision impairment may have difficulty using transportation because the names of the stops on the bus are not announced over the loud speaker, so the person cannot tell when she has reached her destination. The person with the mobility impairment may have difficulty using the transportation system because the buses do not have ramps that would allow her to alight independently with her wheelchair. Despite the fact that these two people have different types of impairments and run into different types of barriers, the _level of disability_ they experience is quite similar in this particular domain of transportation.
The output of Rasch Analysis will give us the disability score for each person in the sample. We can then plot these scores in a histogram to get an overall picture of the distribution of disability in a population. An example of such a distribution is below. You can think of the horizontal axis as a ruler. Each person sits somewhere on this ruler, and the heights of the bars tells how many people are at that particular position on the ruler.
```{r plot-distributionruler, eval=TRUE, echo=FALSE}
include_graphics("Images/distributionruler.png")
```
# Why should we use Rasch Analysis?
## Important properties
The main reason why we use Rasch Analysis has already been mentioned: it allows us to take ordinal data and map it onto an interval scale. However there are other important properties of the Rasch Model that make it a particularly useful method for our purposes:
* No assumptions are made about distribution of person abilities
* Difficulties of two items can be compared independently of abilities of the persons
* Abilities of two people can be compared independently of difficulties of items
* The difference between person abilities and item difficulties is a _sufficient statistic_ (see a statistical text for more information about sufficient statistics)
## Goals
Ultimately we have three main goals when performing Rasch Analysis:
1. Obtain person ability estimates
2. Know the difficulty of items on the scale
3. Create and **validate** an interval-scaled **reliable** measurement tool
Goal 1, in other words, gives us the disability scores we are looking for. Goal 2 tells us how "difficult" items are, meaning how indicative of different levels of disability (mild, moderate, severe) they are.
Goal 3 has to do with the psychometric properties of the survey instrument we are using. With Rasch Analysis, in addition to calculating the interval scale, we are simultaneously performing an analysis of the validity and reliability of the scale. If our data fit the model property, then we can be certain that the scores that we obtain for people and for items are valid (i.e., they are measuring what we intend for them to measure) and reliable (i.e., the survey instrument would give consistent results if the survey was repeated).
## Output
As already mentioned above, one of our aims is to obtain the person ability estimates. This means that an output of the Rasch analysis will be a latent trait continuum (shown below)...
```{r plot-continuum, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum.png")
```
...where you can locate specific people...
```{r plot-continuum-person, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum_person.png")
```
...and also the items!
```{r plot-continuum-personitem, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum_personitem.png")
```
"Latent trait continuum" is another phrase to describe the scale. "Latent trait" refers to an underlying characteristic of the population that the survey instrument is measuring (in our case, disability). "Continuum" is simply another word for "scale", emphasizing that people can be placed at any point between the end points (0 and 100) of the scale.
The figure above is illustrating a toy example analyzing the strength of people and the difficulty of each item (questions Q1 to Q10) in regards to strength. The strongest person is on the left side of the continuum, while the weakest person is on the right side of the continuum. We can see that items Q9 and Q10 are the easiest; they are located on the same end of the continuum as the weakest person. The probability that the strongest people on the left end of the continuum get the questions "correct" is very high. Questions Q1 and Q2 are the hardest; only the strongest people, located on the same end of the continuum, have a reasonable probability of getting these questions "correct."
# What is Rasch Analysis?
Rasch Analysis was named after Danish mathematician Georg Rasch (1901-1980). The fundamental idea of Rasch Analysis was summarized by Rasch as follows:
> ...a person having a greater ability than another person should have the greater probability of solving any item of the type in question, and similarly, one item being more difficult than another means that for any person the probability of solving the second item is the greater one.
This quote from Rasch refers to two situations:
1. If we have two people, Person A and Person B, and Person A has more disability than Person B, then Person A has a greater probability of rating any given item on the survey, for instance "walking 100m," as more difficult than Person B.
2. If we have two items, Item A and Item B, and Item A is more difficult than Item B, then any given person will have a higher probability of rating Item A as more difficult than Item B.
Rasch is one of the simplest models in **Item Response Theory (IRT)**. IRT is a **probabilistic** approach to measurement: the probability of a "correct" response to an item (i.e., question) is a function (i.e., relationship) of the parameters (i.e., characteristics) the person and the item.
Under the Rasch Model, the probability of a certain response to a measurement item is associated with the respondent's ability ($\beta_n$) and the item's difficulty ($\delta_i$). Using our previous example of a mathematics test, the person's ability $\beta_n$ would be the person's mathematical intelligence, and the item's difficulty $\delta_i$ would be the difficulty of any given question on the test.
There are two different versions of the model: the dichotomous version (all questions have two response options, for instance 0 and 1) and the polytomous version (questions have more than 2 response options). The polytomous model, which we are most interested in because in the MDS most questions use a 5-point scale ranging from "1=No problems" to "5=Extreme problems", is simply an extension of the dichotomous version. Below we give a basic overview of the models.
## The Rasch Model - Dichotomous
Below is the main equation for the dichotomous Rasch Model (two response options):
$$P(X_{ni}=1) = \frac{e^{\beta_n-\delta_i}}{1+e^{\beta_n-\delta_i}}$$
where
* $i$ - item counter
* $n$ - person counter
* $X_{ni}$ - random variable of score of person $n$ on item $i$
* $\beta_n$ - location of person $n$ on latent continuum
* $\delta_i$ - difficulty of item $i$ on latent continuum
In simpler terms, this means: the **probability** that person $n$ gets question $i$ correct is a **ratio** based on the difference between that person's ability ($\beta_n$) and the difficulty of that item ($\delta_i$).
This can be seen in the following figure. The vertical axis is the probability of the person getting a question correct ($P(X_{ni}=1)$), ranging from 0 to 1. The horizontal axis is the difference between a person's ability and the item difficulty ($\beta_n-\delta_i$). Let us say that this question has two options: 0 and 1, and a "correct" response to the item is the response option of 1. When the person's ability and the item difficulty are equal ($\beta_n-\delta_i=0$ or $\beta_n=\delta_i$), then the probability that the person gets the question correct is 50%. If the person's ability is higher than the item difficulty ($\beta_n > \delta_i$), then the probability that the person gets the question correct is greater than 50%. If the person's ability is less than the item difficulty ($\beta_n < \delta_i$), then the probability that the person gets the question correct is less than 50%.
``` {r rasch-setup, echo=FALSE, eval=TRUE, out.width = NULL}
x <- seq(-5,5,0.01)
y <- exp(x)/(1+exp(x))
df <- tibble(x,y)
ggplot(df,aes(x=x,y=y)) +
geom_point() +
labs(x="Difference between person ability\n and item difficulty", y="Probability of person getting\n question correct")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
```
## The Rasch Model - Polytomous
The polytomous Rasch Model (more than 2 response options) is an extension of the dichotomous version. It is also known as the **Partial Credit Model**. The main equation for this model is:
$$P(X_{ni}=x) = \frac{e^{\sum^x_{k=0}(\beta_n-\tau_{ki})}}{\sum^{m_i}_{j=0}e^{\sum^j_{k=0}(\beta_n-\tau_{ki})}}$$
where
* $i$ - item counter
* $n$ - person counter
* $X_{ni}$ - random variable of score of person $n$ on item $i$
* $\beta_n$ - location of person $n$ on latent continuum
* $\tau_{ki}$ - $k^{th}$ threshold of item $i$ on latent continuum
* $m_i$ - maximum score for item $i$
In simpler terms, the **probability** that person $n$ gives answer $x$ to question $i$ is a **ratio** based on the difference between that person's ability ($\beta_n$) and the difficulty of each response option ($\tau_{ki}$) for that item.
This can be seen in the following figure, which is similar to the figure for the dichotomous model. The vertical axis is the conditional probability of the person achieving choosing a particular response option or higher ($P(X_{ni}>x)$), ranging from 0 to 1. The horizontal axis is the difference between a person's ability and the item difficulty. The key difference between this figure and the figure for the dichotomous model is that now we have a probability curve for each threshold.
A **threshold** is the point between two adjacent response options where a person has a 50% chance of giving one response option or another. The figure below shows the case of four response options, which means this question has three thresholds (The 50% point between response options 1 and 2, the same point between options 2 and 3, and the same point between options 3 and 4).
In the figure below, you can see that the probability of passing the first threshold (red curve), in other words achieving a score of 2, is always higher than the probability of passing the second (green) or third (blue) threshold. This shows a key property of the polytomous Rasch Model: thresholds are **ordered**.
``` {r rasch-setup-poly, echo=FALSE, eval=TRUE, out.width = NULL}
x <- seq(-5,5,0.01)
tao <- c(-2.5,0,2.5)
y0 <- exp(x-tao[1])/(1+exp(x-tao[1]))
y1 <- exp(x-tao[2])/(1+exp(x-tao[2]))
y2 <- exp(x-tao[3])/(1+exp(x-tao[3]))
df <- tibble(x,y0,y1,y2)
df.long <- df %>%
pivot_longer(!x, names_to = "Threshold", values_to = "y")
ggplot(df.long,aes(x=x,y=y,color=Threshold)) +
geom_point()+
scale_color_discrete(labels=c("First","Second","Third")) +
labs(x="Difference between person ability\n and item difficulty", y="Conditional probability of person\n passing response threshold")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
```
# How do you do Rasch Analysis?
## Overview of the method
Everything we have described so far is background to the rationale of Rasch Analysis. However at this point we have not yet described how it is actually done.
Overall, the basic technique is to **fit our data to the Rasch Model**, taking note of how well it fits the **Rasch Model assumptions**. This differs from other types of modeling where you _fit a model to your data_. The Rasch Model is seen as the "ideal", and we want to adjust our data in such a way that it can fit this ideal. If our data can reasonably fit this ideal, then we can be assured we have a **valid** and **reliable** interval scale.
Rasch Analysis is an **iterative process**, meaning it must be performed multiple times in order to reach a result. The process is shown in the figure below.
``` {r iteration, echo=FALSE, eval=TRUE}
include_graphics("Images/iteration_EN.png")
```
The next question naturally is: what are the Rasch assumptions that we are testing?
## Rasch assumptions
The Rasch Model assumptions are as follows. Each assumption will be discussed in detail in the following sections:
1. Item independence
2. Unidimensionality
3. Stochastic ordering
4. Group invariance
5. Fit to model
We will also discuss below how to adjust data to have it better fit each assumption. These techniques might not make much sense now, but they will become clearer once we go through the example.
### Item independence
Item independence refers to uncorrelation between items. In other words, we want responses to one item to NOT be related strongly with responses in another item. Correlation happens when items are linked by common attributes, content, structures, or themes. For example, in the MDS two items that are often related are "How much of a problem do you have with feeling sad, low or depressed?" and "How much of a problem do you have with feeling worried, nervous or anxious?"
In order to take care of problems with high correlation, we often aggregate dependent items into one "super item", or "testlet". For instance if we have two items, each with 5 response options, that are highly correlated, we could combine them into a testlet by adding up the responses for each person. This testlet would now have 9 response options.
### Unidimensionality
Unidimensionality refers to the situation when all items measure the same underlying single construct. In the case of the MDS, we want all items to be measuring the same underlying construct of "disability". A total score is only meaningful with a unidimensional scale.
Take another example in the educational field: Imagine a math test. All items on this test are measuring the same underlying construct, that is, the person's ability in math. If a math test also contained English literature questions, the scale created with all the items of this test would no longer be unidimensional because the test is composed of two totally separate sets of items.
If we notice problems with the dimensionality of our data, we can correct this by splitting items onto multiple scales. In our educational example above, this would mean creating a separate scale for the math questions on the test and a separate scale for the English questions.
### Stochastic ordering
Stochastic ordering refers to the thresholds (i.e., boundaries between response options) being in the correct order. We expect the probability of a person crossing the first threshold to be higher than the probability they pass the second, and likewise the probability of crossing the second threshold should be higher than the probability of crossing the third, etc. As an analogy, think of a high jump: if someone is able to jump over 1.5m, then they necessarily already jumped over 1m. Stochastic ordering is only relevant for items with more than 2 response options (polytomous case).
```{r plot-highjump, eval=TRUE, echo=FALSE}
include_graphics("Images/highjump.jpg")
```
If we have problems with stochastic ordering, we can recode response options in order to create fewer thresholds between items that are more likely to be in order.
### Group invariance
Group invariance refers to items behaving similarly for people with different characteristics. For example, we want men and women to show similar patterns of responses for an item. If items show different behavior for different groups, this is referred to as "differential item functioning (DIF)".
For the MDS, because we expect men and women to experience different levels of disability, we are not too concerned with group invariance. This is the same for people of different ages, because the older we get, the higher the probability of experiencing disability in daily life.
If we want to correct for DIF, we can split items into subgroups. For instance instead of having one question Q1 for the whole sample, we can split it into two questions Q1_Men and Q1_Women.
### Fit to model
In addition to all the above assumptions, we also care about fit to the model. Fit of items, persons, and the model overall are measured with various fit statistics.
We determine:
* Do **items** fit the model? -> examine item fit
* Do **people** fit the model? -> examine person fit
* How is the model **overall**? -> examine reliability scores, like person separation index (PSI)
If items or people are showing poor fit to the model after making all other adjustments we could make, all that's left to do is delete items or people from the scale. This would be considered a last resort, as it means the scale you end up creating does not examine all the items or people you originally set out to measure.
## Why do I have to run the model multiple times?
It is very rare for the first model you run to give perfect results where everything fits. If your goal is simply to assess the validity and reliability of your questionnaire with the raw data, then you could run the model once and analyze those results. However if your goal is to obtain a valid and reliable score--as it is in the case of the MDS--then it is most often necessary to run the model multiple times, making adjustments to the data each time. We are trying to find a way to fit the data to the Rasch "ideal", in other words to create a score that adheres to these basic assumptions built in to the Rasch model. The fact that you must run the model multiple times does not at all necessarily mean there is something wrong with your questionnaire. The Rasch Analysis process simply tells you how best to utilize survey instrument you have to create the most trustworthy score.
## Where do I start? {#repair}
The figure below shows the repair pathway for the Rasch Model. Overall, you can see that all of these assumptions can affect the performance of other assumptions. However, general guidance about what order to use when adjusting data can be determined.
```{r plot-repair, eval=TRUE, echo=FALSE}
include_graphics("Images/repair.png")
```
Local dependency (or item independence) affects unidimensionality, threshold ordering (or stochastic ordering) and the fit to the model, so it is good to start by taking care of item independence first. Unidimensionality affects threshold ordering and the fit to the model, so it's a good assumption to take care of second. Threshold ordering affects the fit to the model, so it can be taken care of third. Finally, group invariance only affects fit to the model, so it can be taken care of last.
## How do I know when I'm done?
Determining when you can stop running iterations of the Rasch Model is not totally straightforward. There are general rules of thumb we will learn, but it takes practice to get a sense of what is "good enough". The rest of this guide will show you what to look for in order to determine when your data fits the model well enough.
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c1_background_EN.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(whomds)
options(survey.lonely.psu = "adjust")
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
## ----plot-scales, eval=TRUE, echo=FALSE---------------------------------------
include_graphics("Images/scales.png")
## ----plot-ruler, eval=TRUE, echo=FALSE----------------------------------------
include_graphics("Images/ruler.png")
## ----plot-oranges, eval=TRUE, echo=FALSE--------------------------------------
include_graphics("Images/oranges.png")
## ----plot-distributionruler, eval=TRUE, echo=FALSE----------------------------
include_graphics("Images/distributionruler.png")
## ----plot-continuum, eval=TRUE, echo=FALSE------------------------------------
include_graphics("Images/continuum.png")
## ----plot-continuum-person, eval=TRUE, echo=FALSE-----------------------------
include_graphics("Images/continuum_person.png")
## ----plot-continuum-personitem, eval=TRUE, echo=FALSE-------------------------
include_graphics("Images/continuum_personitem.png")
## ----rasch-setup, echo=FALSE, eval=TRUE, out.width = NULL---------------------
x <- seq(-5,5,0.01)
y <- exp(x)/(1+exp(x))
df <- tibble(x,y)
ggplot(df,aes(x=x,y=y)) +
geom_point() +
labs(x="Diferencia entre la capacidad de una persona y la dificultad del ítem", y="Probabilidad de que la persona responda \na una pregunta correctamente")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
## ----rasch-setup-poly, echo=FALSE, eval=TRUE, out.width = NULL----------------
x <- seq(-5,5,0.01)
tao <- c(-2.5,0,2.5)
y0 <- exp(x-tao[1])/(1+exp(x-tao[1]))
y1 <- exp(x-tao[2])/(1+exp(x-tao[2]))
y2 <- exp(x-tao[3])/(1+exp(x-tao[3]))
df <- tibble(x,y0,y1,y2)
df.long <- df %>%
pivot_longer(!x, names_to = "Threshold", values_to = "y")
ggplot(df.long,aes(x=x,y=y,color=Threshold)) +
geom_point()+
scale_color_discrete(labels=c("First","Second","Third")) +
labs(x="Diferencia entre la capacidad de una persona y la dificultad del ítem",
y="Probabilidad condicional de que la persona logre \nelegir una opción de respuesta particular o superior")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
## ----iteration, echo=FALSE, eval=TRUE-----------------------------------------
include_graphics("Images/iteration_ES.png")
## ----plot-highjump, eval=TRUE, echo=FALSE-------------------------------------
include_graphics("Images/highjump.jpg")
## ----plot-repair, eval=TRUE, echo=FALSE---------------------------------------
include_graphics("Images/repair.png")
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c1_background_ES.R
|
---
title: "1 - Antecedentes sobre la medición de discapacidad"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{1 - Antecedentes sobre la medición de discapacidad}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(whomds)
options(survey.lonely.psu = "adjust")
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Introducción
## Antecedentes
En 2011, el proyecto de la Encuesta Modelo sobre la Discapacidad (MDS, por sus siglas en inglés) fue iniciado por la OMS y el Banco Mundial (BM) en 2011.
El MDS se basa en la Clasificación Internacional de Funcionamiento, Discapacidad y Salud (ICF, por sus siglas en inglés) y representa una evolución en el concepto de medición de la discapacidad. Explora la discapacidad como la experiencia de una persona con una condición de salud o discapacidad que se encuentra en un entorno facilitador u obstaculizador, en lugar de centrarse únicamente en el estado de salud de la persona.
En consonancia con el marco conceptual de la ICF, la MDS adopta el enfoque de que:
* La discapacidad no es un atributo interno de una persona sino una experiencia;
* La discapacidad es etiológicamente neutral;
* La discapacidad es un continuo, una cantidad y una cuestión de grado, que va desde la no discapacidad a la discapacidad extrema;
* La discapacidad es universal, lo que significa que cada persona se sienta en algún lugar del continuo de la discapacidad.
Por lo tanto, la razón detrás de la MDS requiere una muestra de población general y el uso de no filtros, es decir, no una selección a priori de los encuestados, con tres objetivos principales:
* Lograr tasas de prevalencia de discapacidad comparables y estandarizadas en todos los países;
* Entregar los datos necesarios para diseñar intervenciones, programas y políticas apropiadas para personas con niveles de discapacidad leves, moderados y graves;
* Supervisar la implementación de los Objetivos de Desarrollo Sostenible (ODS) y la Convención de las Naciones Unidas sobre los Derechos de las Personas con Discapacidad (CRPD, por sus siglas en inglés) al permitir una comparación directa entre las personas con niveles de discapacidad leves, moderados y graves, y las personas sin discapacidad.
La MDS adopta el enfoque de que la discapacidad es un fenómeno universal caracterizado por un continuo que varía de niveles de discapacidad bajos a altos. Esta conceptualización requiere que la información sobre la discapacidad se informe y analice utilizando escalas métricas. Esta escala va desde 0 (sin discapacidad) a 100 (discapacidad extrema).
Siguiendo un enfoque similar al del Informe Mundial sobre Discapacidad (WRD, por sus siglas en inglés) y utilizando la moderna teoría de pruebas, las preguntas de funcionamiento del Módulo 4000 se utilizan para construir una escala de discapacidad con propiedades métricas. La muestra de la población general se utiliza para crear esta métrica, que luego se transforma linealmente para ir desde 0 (nivel más bajo de discapacidad) hasta 100 (nivel más alto).
## Propósito de esta guía
El Programa de Discapacidad de la OMS ofrece apoyo técnico a los países para guiar la implementación exitosa de la encuesta y analizar los datos resultantes. Esta guía forma parte de este paquete de apoyo técnico.
Para crear la escala de discapacidad, en la que cada individuo tiene una puntuación de 0 a 100, la OMS utiliza una técnica llamada Análisis de Rasch. El propósito de esta guía es explicar en detalle cómo se realiza el Análisis de Rasch y cómo utilizar el paquete de códigos de la OMS, escrito en el lenguaje de programación estadística `R`, para llevar a cabo el Análisis de Rasch para el MDS.
## Los objetivos
1. Comprender la medición y la información que los diferentes tipos de escalas pueden proporcionar;
2. Describir el razonamiento y el proceso detrás del Análisis Rasch;
3. Aprender a preparar datos para un modelo de Rasch;
4. Aprender a ejecutar un modelo Rasch;
5. Aprender a evaluar la calidad del modelo de Rasch;
6. Aprender a ajustar los datos para mejorar la calidad de un modelo de Rasch;
7. Comprender cómo usar el paquete para calcular estadísticas descriptivas.
# ¿Qué es la medición?
A primera vista, la medición parece muy directa. Sin embargo, el concepto de "medición" en realidad se compone de unos pocos componentes más pequeños. Es importante entender cada uno de estos componentes al formular una nueva herramienta de medición, como lo estamos haciendo con la Encuesta Modelo sobre Discapacidad.
Las principales ideas de medición son las siguientes:
* Los **objetos** tienen **propiedades** que se pueden pensar en términos de más o menos, más grandes o más pequeños, más fuertes o más débiles.
* Esta **propiedad** puede medirse a través de su **manifestación** (o comportamiento observable).
* Esta **manifestación** se puede mapear en una **escala**.
* **Medición** puede tener algún **error** involucrado, y puede no ser perfectamente preciso.
Por ejemplo, una persona (**objeto**) tiene cierta inteligencia con respecto a las matemáticas (**propiedad**). La inteligencia matemática de esta persona se puede observar a través de su desempeño en una prueba de matemáticas (**manifestación**). Su desempeño en el examen de matemáticas recibe una puntuación de 0 a 100 (**escala**). El puntaje que alguien recibe en un día en particular puede estar influenciado por factores aleatorios como su estado de ánimo o las condiciones de la habitación, por lo que el puntaje puede no reflejar exactamente la verdadera inteligencia de la persona (**error**).
Así como hay diferentes tipos de **propiedades** que los objetos pueden tener (por ejemplo: altura, peso, color, inteligencia), también hay diferentes tipos de **escalas** con las que se pueden medir estas propiedades. Cada uno de estos diferentes tipos de escalas puede proporcionarle diferentes tipos de información, y solo puede realizar ciertos tipos de operaciones matemáticas con cada tipo de escala.
Los cuatro tipos principales de escalas son:
* **Escala nominal** - Esta escala implica asignar nombres a objetos. Por ejemplo, en una encuesta a menudo identificamos a las personas como "hombres" o "mujeres". Esto sería considerado una escala nominal. La única operación matemática disponible para esta escala es la evaluación de la igualdad. En otras palabras, con escalas nominales, solo puede determinar si dos objetos son iguales o no lo son.
* **Escala ordinal** - Esta escala implica colocar objetos en un orden particular. Por ejemplo, en una encuesta a menudo tiene preguntas con las siguientes opciones de respuesta: "No estar para nada de acuerdo", "No estar de acuerdo", "Ni de acuerdo ni en desacuerdo", "De acuerdo" y "Estar totalmente de acuerdo". Esta sería una escala ordinal. Hay dos operaciones matemáticas posibles con escalas ordinales: igualdad y más/menos. Por ejemplo, con esta escala puede determinar si dos objetos dan respuestas iguales (por ejemplo, dos personas que responden "de acuerdo" a una pregunta en una encuesta) o si la respuesta de una persona es "mayor" que la de otra. Por ejemplo, si la Persona A responde "de acuerdo" y la Persona B responde "estar totalmente de acuerdo", puede estar seguro de que la Persona B acepta más el elemento que la Persona A. Sin embargo, no puede determinar la "distancia" entre los ítems. En otras palabras, tomando nuestro ejemplo, no sabe cuánto más concuerda la Persona B que la Persona A.
* **Escala de intervalo**: Esta escala implica colocar objetos en posiciones que tienen un orden significativo y distancia con respecto a otros objetos. Por ejemplo, el clima en dos días puede tener dos temperaturas diferentes. Digamos que el Día 1 tiene una temperatura de 10 grados centígrados y el Día 2 tiene una temperatura de 20 grados centígrados. Este es un ejemplo de una escala de intervalo. Con esta escala, podemos usar tres operaciones matemáticas diferentes: podemos determinar si dos objetos son iguales, si uno es mayor que otro, y también la distancia relativa entre ellos. En nuestro ejemplo, claramente el Día 1 y el Día 2 tienen dos temperaturas diferentes, y el Día 2 es más caluroso que el Día 1. Pero incluso más que eso, podemos decir que el Día 2 es exactamente 10 grados centígrados más caluroso que el Día 1. A diferencia de una escala ordinal, la distancia entre dos puntos en la escala es significativa. Sin embargo, no podemos determinar relaciones entre dos puntos en la escala. En nuestro ejemplo, no podemos decir que el Día 2 fue el doble de caliente que el Día 1. Esto se debe a que 0 grados se colocan arbitrariamente. Cuando hace 0 grados afuera, hace frío, pero todavía hay una temperatura presente.
* **Escala de cociente** - Esta escala es como una escala de intervalo, excepto que también tiene un punto "0" significativo. Podemos aplicar cuatro operaciones matemáticas diferentes a esta escala: las tres de una escala de intervalo además de la multiplicación/división. Por ejemplo, imagine que la Persona A mide 100 cm de altura y la Persona B mide 150 cm de altura. Claramente podemos determinar que la Persona A no es la misma altura que la Persona B, la Persona A es más baja que la Persona B y la Persona A es 50 cm más baja que la Persona B. Pero incluso más que eso, porque 0 cm es significativo, podemos decir que Persona B es 50% más alto que la Persona A. Podemos crear una proporción entre sus alturas. A diferencia de la temperatura, podemos decir con certeza dónde está 0 cm. Si algo mide 0 cm, ¡entonces no está!
La siguiente tabla ofrece un resumen de qué tipo de información es posible con cada escala.
```{r plot-scales, eval=TRUE, echo=FALSE}
include_graphics("Images/scales.png")
```
La mayoría de las preguntas de la MDS están en una escala ordinal de 5 puntos (por ejemplo, 1 = Ninguna, 2 = Algunas, 3 = Moderada, 4 = Mucho, 5 = Completa). Para crear un puntaje que podamos usar y confiar, lo que queremos hacer es **tomar nuestros datos ordinales y mapearlos en una escala de intervalos** de discapacidad. En otras palabras, al usar la regla de abajo como referencia, queremos pasar de la parte superior de la regla a la parte inferior.
```{r plot-ruler, eval=TRUE, echo=FALSE}
include_graphics("Images/ruler.png")
```
¿Por qué simplemente agregar datos ordinales no es lo suficientemente bueno? Imagine que es el CEO de una empresa que vende jugo de naranja. Le pregunta a sus empleados, ¿cuánto jugo de naranja podremos producir este trimestre? El Empleado A responde que la compañía ha producido **5000 naranjas** mientras que el Empleado B responde que la compañía ha producido **1500kg de naranjas**. ¿Quién le dio más información sobre la cantidad de jugo de naranja que podrá producir?
El Empleado B le dio información sobre una escala de intervalo (peso), y el Empleado A le dio información sobre una escala ordinal (conteo). El Empleado B le dio más información; Con su respuesta, usted sabe exactamente cuánto jugo de naranja puede vender. El Empleado A le dijo cuántas naranjas tiene, pero no tiene idea de cuán grandes o pequeñas son.
```{r plot-oranges, eval=TRUE, echo=FALSE}
include_graphics("Images/oranges.png")
```
Este escenario es similar a nuestro cuestionario. Podríamos simplemente sumar todas las respuestas a todas las preguntas que nos interesan para calcular una puntuación total. Sin embargo, esa puntuación total no nos dice mucho sobre el nivel general de discapacidad que una persona experimenta, porque no sabemos qué preguntas se identificaron como difíciles y las diferentes preguntas tienen diferentes niveles de dificultad.
Por ejemplo, imagine que una persona está respondiendo preguntas de la Encuesta Modelo sobre la Discapacidad. Esta persona respondió "3 = Algunos problemas" a las dos preguntas: "¿Qué tan problemático ha sido para usted utilizar el servicio sanitario?" y "¿Qué tan problemático ha sido para usted dormir?". Uno puede imaginar que las dificultades para dormir son bastante comunes, y muchos de nosotros experimentamos problemas con el sueño sin que esto afecte nuestras vidas demasiado. Sin embargo, muchas menos personas tienen "algunos problemas" con el uso del inodoro, y uno puede imaginar que tener incluso un cierto nivel de dificultad para usar el inodoro puede causar problemas significativos en la vida de alguien. Por lo tanto, se puede ver que la respuesta de "3" a "dormir" no es equivalente a la respuesta de "3" a "utilizar el servicio sanitario".
Así que, en esencia, estamos tratando de pasar de contar las respuestas a las preguntas sobre discapacidad a medir realmente los niveles de discapacidad en una escala de intervalo. Lo haremos usando **Análisis Rasch**.
# ¿Cómo se aplica una escala de intervalo para medir la discapacidad?
Antes de comenzar la discusión de la técnica del Análisis de Rasch, es importante enfatizar nuevamente la comprensión de la OMS sobre la discapacidad. Estamos midiendo la discapacidad en una **escala de intervalo**. Esta escala varía de 0 (sin discapacidad) a 100 (discapacidad extrema), y cada persona de la población se encuentra en algún lugar de la escala.
Esto es muy diferente de la forma tradicional de pensar sobre la discapacidad. A menudo, cuando las personas escuchan la palabra "discapacidad", piensan en diferentes "tipos de discapacidades", y las personas que más rápidamente vienen a la mente son, por ejemplo, las personas ciegas, las personas sordas o las que usan sillas de ruedas. Para la OMS, la palabra "discapacidad" no se refiere a los atributos de grupos específicos y limitados de personas que tienen discapacidades particulares. Para la OMS, "discapacidad" se refiere a una experiencia universal, no un atributo de una persona, que es el resultado de una multitud de factores, como una condición de salud subyacente o la accesibilidad de un entorno.
Por ejemplo, piense en una persona que tiene un impedimento de la vista debido a un glaucoma y otra persona que tiene un impedimento de movilidad debido a una lesión de la médula espinal. Ambas personas pueden tener dificultades para usar el sistema de transporte. La persona con una discapacidad visual puede tener dificultades para usar el transporte porque los nombres de las paradas en el autobús no se anuncian por el altavoz, por lo que la persona no puede saber cuándo ha llegado a su destino. La persona con problemas de movilidad puede tener dificultades para usar el sistema de transporte porque los autobuses no tienen rampas que le permitan bajar independientemente con su silla de ruedas. A pesar del hecho de que estas dos personas tienen diferentes tipos de impedimentos y se enfrentan con diferentes tipos de barreras, el _nivel de discapacidad_ que experimentan es bastante similar en este dominio particular del transporte.
La salida del Análisis Rasch nos dará el puntaje de discapacidad para cada persona en la muestra. Luego podemos trazar estos puntajes en un histograma para obtener una imagen general de la distribución de la discapacidad en una población. A continuación se muestra un ejemplo de dicha distribución. Puedes pensar en el eje horizontal como una regla. Cada persona se sienta en algún lugar de esta regla, y las alturas de los barrotes indican cuántas personas se encuentran en esa posición particular en la regla.
```{r plot-distributionruler, eval=TRUE, echo=FALSE}
include_graphics("Images/distributionruler.png")
```
# ¿Por qué debemos usar el Análisis de Rasch?
## Propiedades importantes
La razón principal por la que usamos Rasch Analysis ya se ha mencionado: nos permite tomar datos ordinales y mapearlos en una escala de intervalo. Sin embargo, hay otras propiedades importantes del Modelo Rasch que lo convierten en un método particularmente útil para nuestros propósitos:
* No se hacen suposiciones sobre la distribución de las capacidades de personas.
* Las dificultades de dos ítems pueden compararse independientemente de las capacidades de las personas
* Las capacidades de dos personas se pueden comparar independientemente de las dificultades de los ítems
* La diferencia entre las capacidades de las personas y las dificultades de los ítems es una _estadística suficiente_ (consulte un texto estadístico para obtener más información sobre estadísticas suficientes)
## Metas
En última instancia, tenemos tres objetivos principales al realizar el Análisis Rasch:
1. Obtener estimaciones de las capacidades de la personas
2. Conocer la dificultad de los ítems en la escala.
3. Crear y **validar** una herramienta de medición **confiable** de escala de intervalos
En otras palabras, la Meta 1 nos da los puntajes de discapacidad que estamos buscando. La Meta 2 nos dice qué "difíciles" los ítems son, es decir, qué tan indicativos son los diferentes niveles de discapacidad (leve, moderada, grave).
La Meta 3 tiene que ver con las propiedades psicométricas del instrumento de encuesta que estamos utilizando. Con el Análisis Rasch, además de calcular la escala de intervalo, estamos realizando simultáneamente un análisis de la validez y confiabilidad de la escala. Si nuestros datos se ajustan a la propiedad del modelo, podemos estar seguros de que los puntajes que obtenemos para las personas y para los artículos son válidos (es decir, están midiendo lo que pretendemos medir) y confiables (es decir, el instrumento de la encuesta daría resultados consistentes si la encuesta fue repetida).
## Salida
Como ya se mencionó anteriormente, uno de nuestros objetivos es obtener las estimaciones de las capacidades de las personas. Esto significa que una salida del Análisis de Rasch será un continuo de rasgo latente (se muestra a continuación) ...
```{r plot-continuum, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum.png")
```
... donde puede localizar personas específicas ...
```{r plot-continuum-person, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum_person.png")
```
...y también los ítems!
```{r plot-continuum-personitem, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum_personitem.png")
```
"Continuo del rasgo latente" es otra frase para describir la escala. "Rasgo latente" se refiere a una característica subyacente de la población que el instrumento de la encuesta está midiendo (en nuestro caso, discapacidad). "Continuo" es simplemente otra palabra para "escala", enfatizando que las personas pueden ubicarse en cualquier punto entre los puntos finales (0 y 100) de la escala.
La figura anterior ilustra un ejemplo que analiza la fuerza de las personas y la dificultad de cada elemento (preguntas Q1 a Q10) en relación con la fuerza. La persona más fuerte está en el lado izquierdo del continuo, mientras que la persona más débil está en el lado derecho del continuo. Podemos ver que los artículos Q9 y Q10 son los más fáciles; están ubicados en el mismo extremo del continuo que la persona más débil. La probabilidad de que las personas más fuertes en el extremo izquierdo del continuo obtengan las preguntas "correctas" es muy alta. Las preguntas Q1 y Q2 son las más difíciles; solo las personas más fuertes, ubicadas en el mismo extremo del continuo, tienen una probabilidad razonable de que estas preguntas sean "correctas".
# ¿Qué es el Análisis de Rasch?
El Análisis de Rasch fue nombrado por el matemático danés Georg Rasch (1901-1980). La idea fundamental del Análisis de Rasch fue resumida por Rasch de la siguiente manera:
> ... una persona que tenga una capacidad mayor que otra persona debería tener la mayor probabilidad de resolver cualquier elemento del tipo en cuestión y, de manera similar, un elemento es más difícil que otro significa que para cualquier persona la probabilidad de resolver el segundo elemento es el mayor.
Esta cita de Rasch se refiere a dos situaciones:
1. Si tenemos dos personas, la Persona A y la Persona B, y la Persona A tiene más discapacidad que la Persona B, entonces la Persona A tiene una mayor probabilidad de calificar cualquier artículo dado en la encuesta, por ejemplo, "caminar 100 m", como más difícil que la persona B.
2. Si tenemos dos ítems, el Ítem A y el Ítem B, y el Ítem A es más difícil que el Ítem B, entonces cualquier persona tendrá una mayor probabilidad de calificar el Ítem A como más difícil que el Ítem B.
Rasch es uno de los modelos más simples en **Teoría de la respuesta del artículo (IRT, por sus siglas en inglés)**. IRT es un enfoque de medición **probabilístico**: la probabilidad de una respuesta "correcta" a un elemento (es decir, una pregunta) es una función (es decir, una relación) de los parámetros (es decir, las características) de la persona y el elemento.
Bajo el Modelo de Rasch, la probabilidad de cierta respuesta a un elemento de medición está asociada con la capacidad del encuestado ($\beta_n$) y la dificultad del ítem ($\delta_i$). Usando nuestro ejemplo anterior de una prueba de matemáticas, la capacidad de la persona $\beta_n$ sería la inteligencia matemática de la persona, y la dificultad del ítem $\delta_i$ sería la dificultad de cualquier pregunta dada en la prueba.
Hay dos versiones diferentes del modelo: la versión dicotómica (todas las preguntas tienen dos opciones de respuesta, por ejemplo 0 y 1) y la versión politómica (las preguntas tienen más de 2 opciones de respuesta). El modelo politómico, en el que estamos más interesados porque en el MDS la mayoría de las preguntas utiliza una escala de 5 puntos que va desde "1 = sin problemas" a "5 = problemas extremos", es simplemente una extensión de la versión dicotómica. A continuación damos una descripción básica de los modelos.
## El Modelo Rasch - Dicotómico
A continuación se muestra la principal ecuación para el Modelo de Rasch dicotómico (dos opciones de respuesta):
$$P(X_{ni}=1) = \frac{e^{\beta_n-\delta_i}}{1+e^{\beta_n-\delta_i}}$$
en la que:
* $i$ - contador de ítems
* $n$ - contador de personas
* $X_{ni}$ - variable aleatoria del puntaje de la persona $n$ en ítem $i$
* $\beta_n$ - la ubicación de la persona $n$ en el continuo latente
* $\delta_i$ - la dificultad de ítem $i$ en el continuo latente
En palabras más simples, esto significa: la **probabilidad** de que esa persona $n$ responde a la pregunta $i$ correctamente es una **proporción** basada en la diferencia entre la capacidad de esa persona ($\beta_n$) y la dificultad de esa artículo ($\delta_i$).
Esto se puede ver en la siguiente figura. El eje vertical es la probabilidad de que la persona responda a una pregunta correctamente ($P(X_{ni}=1)$), con un rango de 0 a 1. El eje horizontal es la diferencia entre la capacidad de una persona y la dificultad del ítem ($\beta_n-\delta_i$). Digamos que esta pregunta tiene dos opciones: 0 y 1, y una respuesta "correcta" al elemento es la opción de respuesta de 1. Cuando la capacidad de la persona y la dificultad del elemento son iguales ($\beta_n-\ delta_i=0$ o $\beta_n=\delta_i$), entonces la probabilidad de que la persona responda correctamente a la pregunta es del 50%. Si la capacidad de la persona es mayor que la dificultad del elemento ($\beta_n>\delta_i$), entonces la probabilidad de que la persona responda correctamente a la pregunta es superior al 50%. Si la capacidad de la persona es menor que la dificultad del ítem ($\beta_n<\delta_i$), entonces la probabilidad de que la persona responda correctamente a la pregunta es menor al 50%.
``` {r rasch-setup, echo=FALSE, eval=TRUE, out.width = NULL}
x <- seq(-5,5,0.01)
y <- exp(x)/(1+exp(x))
df <- tibble(x,y)
ggplot(df,aes(x=x,y=y)) +
geom_point() +
labs(x="Diferencia entre la capacidad de una persona y la dificultad del ítem", y="Probabilidad de que la persona responda \na una pregunta correctamente")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
```
## El Modelo Rasch - Politómico
El modelo de Rasch politómico (más de 2 opciones de respuesta) es una extensión de la versión dicotómica. También es conocido como el **Modelo de crédito parcial**. La principal ecuación para este modelo es:
$$P(X_{ni}=x) = \frac{e^{\sum^x_{k=0}(\beta_n-\tau_{ki})}}{\sum^{m_i}_{j=0}e^{\sum^j_{k=0}(\beta_n-\tau_{ki})}}$$
en la que:
* $i$ - contador de ítems
* $n$ - contador de personas
* $X_{ni}$ - variable aleatoria de el puntaje de la persona $n$ en ítem $i$
* $\beta_n$ - la ubicación de la persona $n$ en el continuo latente
* $\tau_{ki}$ - $k^{th}$ el umbral de ítem $i$ en el continuo latente
* $m_i$ - el puntaje máximo del ítem $i$
En palabras más simples, la **probabilidad** de que esa persona $n$ dé la respuesta $x$ a la pregunta $i$ es una **proporción** basada en la diferencia entre la capacidad de esa persona ($\beta_n$) y la dificultad de cada opción de respuesta ($\tau_{ki}$) para ese ítem.
Esto se puede ver en la siguiente figura, que es similar a la figura para el modelo dicotómico. El eje vertical es la probabilidad condicional de que la persona logre elegir una opción de respuesta particular o superior ($P(X_{ni}>x)$), que va de 0 a 1. El eje horizontal es la diferencia entre la capacidad de una persona y la dificultad del ítem. La diferencia clave entre esta figura y la figura para el modelo dicotómico es que ahora tenemos una curva de probabilidad para cada umbral.
Un **umbral** es el punto entre dos opciones de respuesta adyacentes donde una persona tiene un 50% de probabilidad de dar una opción de respuesta u otra. La siguiente figura muestra el caso de cuatro opciones de respuesta, lo que significa que esta pregunta tiene tres umbrales (el 50% del punto entre las opciones de respuesta 1 y 2, el mismo punto entre las opciones 2 y 3, y el mismo punto entre las opciones 3 y 4).
En la siguiente figura, puede ver que la probabilidad de pasar el primer umbral (curva roja), es decir, obtener una puntuación de 2, es siempre mayor que la probabilidad de pasar el segundo (verde) o el tercer (azul) umbral. Esto muestra una propiedad clave del Modelo de Rasch politómico: los umbrales están **ordenados**.
``` {r rasch-setup-poly, echo=FALSE, eval=TRUE, out.width = NULL}
x <- seq(-5,5,0.01)
tao <- c(-2.5,0,2.5)
y0 <- exp(x-tao[1])/(1+exp(x-tao[1]))
y1 <- exp(x-tao[2])/(1+exp(x-tao[2]))
y2 <- exp(x-tao[3])/(1+exp(x-tao[3]))
df <- tibble(x,y0,y1,y2)
df.long <- df %>%
pivot_longer(!x, names_to = "Threshold", values_to = "y")
ggplot(df.long,aes(x=x,y=y,color=Threshold)) +
geom_point()+
scale_color_discrete(labels=c("First","Second","Third")) +
labs(x="Diferencia entre la capacidad de una persona y la dificultad del ítem",
y="Probabilidad condicional de que la persona logre \nelegir una opción de respuesta particular o superior")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
```
# ¿Cómo se hace el Análisis de Rasch?
## El resumen del método
Todo lo que hemos descrito hasta ahora es un trasfondo de la lógica del Análisis de Rasch. Sin embargo, en este punto aún no hemos descrito cómo se lo hace realmente.
En general, la técnica básica es **ajustar nuestros datos al Modelo Rasch**, tomando nota de lo bien que se ajusta a las **suposiciones del Modelo Rasch**. Esto difiere de otros tipos de modelado en los que se adapta un modelo a sus datos. El modelo de Rasch se ve como el "ideal", y queremos ajustar nuestros datos de manera que puedan ajustarse a este ideal. Si nuestros datos se ajustan razonablemente a este ideal, podemos estar seguros de que tenemos una escala de intervalo **válida** y **confiable**.
El análisis de Rasch es un **proceso iterativo**, lo que significa que debe realizarse varias veces para alcanzar un resultado. El proceso se muestra en la siguiente figura.
``` {r iteration, echo=FALSE, eval=TRUE}
include_graphics("Images/iteration_ES.png")
```
La siguiente pregunta, naturalmente, es: ¿cuáles son los suposiciones de Rasch que estamos probando?
## Las suposiciones de Rasch
Los suposiciones del Modelo Rasch son los siguientes. Cada suposición será discutido en detalle en las siguientes secciones:
1. Independencia de ítems
2. Unidimensionalidad
3. Ordenamiento estocástico
4. Invariación de grupo
5. Ajuste al modelo
También analizaremos a continuación cómo ajustar los datos para que se ajusten mejor a cada supuesto. Es posible que estas técnicas no tengan mucho sentido ahora, pero se aclararán una vez que analicemos el ejemplo.
### Independencia de ítems
Independencia de los ítems se refiere a la incorrelación entre los ítems. En otras palabras, queremos que las respuestas a un ítem NO se relacionen fuertemente con las respuestas de otro ítem. La correlación ocurre cuando los ítems están vinculados por atributos, contenido, estructuras o temas comunes. Por ejemplo, en el MDS dos ítems que a menudo están relacionados son "¿Qué tan problemático ha sido para usted sentir tristeza, desánimo o depresión?" y "¿Qué tan problemático ha sido para usted sentir preocupación, nerviosismo o ansiedad?"
Para solucionar problemas con alta correlación, a menudo agregamos ítems dependientes en un "súper ítem" o "testlet". Por ejemplo, si tenemos dos ítems, cada uno con 5 opciones de respuesta, que están altamente correlacionados, podríamos combinarlos en un testlet sumando las respuestas para cada persona. Este testlet ahora tendría 9 opciones de respuesta.
### Unidimensionalidad
La unidimensionalidad se refiere a la situación en la que todos los ítems miden la misma construcción única subyacente. En el caso de la MDS, queremos que todos los ítems midan la misma construcción subyacente de "discapacidad". Una puntuación total solo es significativa con una escala unidimensional.
Toma otro ejemplo en la situación educativo: imagine una prueba de matemáticas. Todos los ítems de esta prueba miden la misma construcción subyacente, es decir, la capacidad de la persona en matemáticas. Si una prueba de matemáticas también contuviera preguntas de literatura en inglés, la escala creada con todos los ítems de esta prueba ya no sería unidimensional porque la prueba se compone de dos conjuntos de ítems totalmente separados.
Si notamos problemas con la dimensionalidad de nuestros datos, podemos corregirlo dividiendo los ítems en múltiples escalas. En nuestro ejemplo educativo anterior, esto significaría crear una escala separada para las preguntas de matemáticas en la prueba y una escala separada para las preguntas de inglés.
### Ordenamiento estocástico
El ordenamiento estocástico se refiere a los umbrales (es decir, los límites entre las opciones de respuesta) que están en el orden correcto. Esperamos que la probabilidad de que una persona cruce el primer umbral sea mayor que la probabilidad de que pase el segundo, y de igual manera la probabilidad de cruzar el segundo umbral debe ser mayor que la probabilidad de cruzar el tercero, etc. Como analogía, piense en un salto de altura: si alguien puede saltar más de 1.5 m, entonces necesariamente ya saltó más de 1 m. El ordenamiento estocástico solo es relevante para los artículos con más de 2 opciones de respuesta (caso politómico).
```{r plot-highjump, eval=TRUE, echo=FALSE}
include_graphics("Images/highjump.jpg")
```
Si tenemos problemas con el ordenamiento estocástico, podemos recodificar las opciones de respuesta para crear menos umbrales entre los ítems que es más probable que estén en orden.
### Invariancia de grupo
La invariancia de grupo se refiere a ítems que se comportan de manera similar para personas con diferentes características. Por ejemplo, queremos que hombres y mujeres muestren patrones similares de respuestas para un ítem. Si los elementos muestran un comportamiento diferente para diferentes grupos, esto se conoce como "funcionamiento diferencial de ítems (DIF, por sus siglas en inglés)".
Para la MDS, debido a que esperamos que los hombres y las mujeres experimenten diferentes niveles de discapacidad, no estamos demasiado preocupados por la invarianza del grupo. Esto es lo mismo para personas de diferentes edades, ya que a medida que envejecemos, mayor es la probabilidad de experimentar una discapacidad en la vida diaria.
Si queremos corregir el DIF, podemos dividir los elementos en subgrupos. Por ejemplo, en lugar de tener una pregunta Q1 para toda la muestra, podemos dividirla en dos preguntas Q1_Men y Q1_Women.
### Ajuste al modelo
Además de todas las suposiciones anteriores, también nos preocupamos por el ajuste al modelo. El ajuste de los ítems, las personas y el modelo en general se miden con diversas estadísticas de ajuste.
Nosotros determinamos:
* ¿Los **ítems** se ajustan al modelo? -> examinar el ajuste de ítems
* ¿Las **personas** se ajustan al modelo? -> examinar el ajuste de personas
* ¿Cómo es el modelo **en general**? -> examinar los puntajes de confiabilidad, como el índice de separación de personas (PSI, por sus siglas en inglés)
Si los ítems o las personas se muestran mal ajustados al modelo después de realizar todos los demás ajustes que podríamos hacer, todo lo que queda por hacer es eliminar ítems o personas de la escala. Esto se consideraría un último recurso, ya que significa que la escala que termina creando no examina todos los ítems o personas que originalmente se propuso medir.
## ¿Por qué tengo que ejecutar el modelo varias veces?
Es muy raro que el primer modelo que ejecute dé resultados perfectos donde todo se ajusta. Si su objetivo es simplemente evaluar la validez y confiabilidad de su cuestionario con los datos sin procesar, entonces podría ejecutar el modelo una vez y analizar esos resultados. Sin embargo, si su objetivo es obtener una puntuación válida y confiable, como ocurre en el caso del MDS, lo más frecuente es que sea necesario ejecutar el modelo varias veces, haciendo ajustes a los datos cada vez. Estamos tratando de encontrar una manera de ajustar los datos al "ideal" de Rasch, en otras palabras, para crear una puntuación que se adhiera a estas suposiciones básicas incorporadas en el modelo de Rasch. El hecho de que deba ejecutar el modelo varias veces no significa necesariamente que haya algún problema con su cuestionario. El proceso de Análisis de Rasch simplemente le indica la mejor manera de utilizar el instrumento de encuesta que tiene para crear la puntuación más confiable.
## ¿Dónde empiezo? {#repair}
La siguiente figura muestra la ruta de reparación para el modelo de Rasch. En general, puede ver que todas estas suposiciones pueden afectar el desempeño de otras suposiciones. Sin embargo, se puede determinar una guía general sobre qué orden usar cuando se ajustan los datos.
```{r plot-repair, eval=TRUE, echo=FALSE}
include_graphics("Images/repair.png")
```
La dependencia local (o independencia del ítem) afecta la unidimensionalidad, el ordenamiento de umbrales (o el ordenamiento estocástico) y el ajuste al modelo, por lo que es bueno comenzar por cuidar en primer lugar la independencia del ítem La unidimensionalidad afecta el ordenamiento de umbrales y el ajuste al modelo, por lo que es una buena suposición cuidar en segundo lugar. El ordenamiento de umbrales afecta el ajuste al modelo, por lo que puede ser atendido en tercer lugar. Finalmente, la invariancia de grupo solo afecta el ajuste al modelo, por lo que puede ser atendido en último lugar.
## ¿Cómo puedo saber cuándo he terminado?
Determinar cuándo puede dejar de ejecutar iteraciones del Modelo Rasch no es totalmente sencillo. Aprenderemos reglas generales, pero se necesita práctica para tener una idea de lo que es "suficientemente bueno". El resto de esta guía le mostrará lo que debe examinar para determinar cuándo sus datos se ajustan al modelo lo suficientemente bien.
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c1_background_ES.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
## ----install-cran-------------------------------------------------------------
# install.packages("whomds")
## ----open-whomds--------------------------------------------------------------
# library(whomds)
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c2_getting_started_EN.R
|
---
title: "2 - Getting started with WHO package for Rasch Analysis"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{2 - Getting started with WHO package for Rasch Analysis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Introduction
WHO performs the Rasch Analysis for the Model Disability Survey using the software `R`. `R` is an open source, statistical programming software. How to program in `R` is beyond the scope of this guide. However the codes we will discuss as follows have been written in such a way to require minimal programming knowledge, and this guide tries to make the instructions for how to use them as simple as possible.
To learn about `R`, please see the references provided at the end of this guide.
To use the package provided by WHO, `R` must be installed from the [Comprehensive R Archive Network (CRAN)](https://cran.r-project.org). We also recommend installing [RStudio](https://posit.co/download/rstudio-desktop/), a very popular integrated development environment (IDE), for `R`. One can think of the relationship between `R` and `RStudio` like a car: `R` is the engine of the car, while `RStudio` is the dashboard and controls. `RStudio` cannot be run without `R`, but it makes `R` easier to use. Both are free to install and use indefinitely.
# What is a package and how do I install one?
A "package" is a collection of `R` functions, data and code with a specific purpose and in a well-defined format. There are thousands of packages for `R` that have been written by `R` users. People write packages in order to share codes they have written that make specific tasks easier. WHO has written a package in order to make analysis of the data from the MDS easier. The package written by WHO is called `whomds`. To install the package, run the following code in the console:
```{r install-cran}
install.packages("whomds")
```
# Using `whomds`
Once `whomds` is installed, it can be opened with the following code:
```{r open-whomds}
library(whomds)
```
`whomds` contains three kinds of functions:
* `table_*()` functions - produce different fit-for-purpose tables
* `fig_*()` functions - produce different fit-for-purpose figures
* `rasch_*()` functions - used when performing Rasch Analysis
In this section we will focus on the `rasch_*()` functions.
There are two sets of `rasch_*()` functions in the `whomds` package: one set for adults, and one set for children. The reason different functions are needed for each group is that the type of Rasch Analysis performed for each group is different. The Rasch Analysis performed for adults is straightforward; the whole adult population can be considered in one group. The Rasch Analysis for children requires a more complicated analysis, because children at different ages are very different, and they can perform vastly different types of activities. First we will describe the analysis of adults, and then describe the analysis of children.
## Package dependencies
The package `whomds` depends on several other packages to run properly. When `whomds` is installed, all of the other packages it uses will also be installed. Be sure that these other packages are installed correctly by investigating any errors that arise during installation.
The additional packages are:
* `colorspace`
* `dplyr`
* `eRm`
* `ggraph`
* `ggplot2`
* `GPArotation`
* `grDevices`
* `igraph`
* `nFactors`
* `plyr`
* `polycor`
* `purrr`
* `RColorBrewer`
* `readr`
* `rlang`
* `scales`
* `srvyr`
* `stringr`
* `TAM`
* `tibble`
* `tidygraph`
* `tidyr`
* `WrightMap`
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c2_getting_started_EN.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
## ----install-cran-------------------------------------------------------------
# install.packages("whomds")
## ----open-whomds--------------------------------------------------------------
# library(whomds)
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c2_getting_started_ES.R
|
---
title: "2 - Empezar con el paquete de OMS para Análisis Rasch"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{2 - Empezar con el paquete de OMS para Análisis Rasch}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Introducción
La OMS realiza el Análisis de Rasch para la Encuesta Modelo sobre la Discapacidad utilizando el software `R`. `R` es un software de programación estadística de código abierto. Cómo programar en `R` está fuera del alcance de esta guía. Sin embargo, los códigos que analizaremos a continuación se han escrito de tal manera que requieren un conocimiento mínimo de programación, y esta guía trata de hacer que las instrucciones sobre cómo usarlas sean lo más simples posible.
Para obtener información sobre `R`, consulte las referencias proporcionadas al final de esta guía.
Para usar el paquete provisto por la OMS, `R` debe instalarse en el [Comprehensive R Archive Network (CRAN)](https://cran.r-project.org). También recomendamos instalar [RStudio](https://posit.co/download/rstudio-desktop/), un _integrated development environment (IDE)_ muy popular, para `R`. Se puede pensar en la relación entre `R` y` RStudio` como un automóvil: `R` es el motor del automóvil, mientras que` RStudio` es el tablero y los controles. `RStudio` no se puede ejecutar sin `R`, pero hace que `R` sea más fácil de usar. Ambos son gratis de instalar y usar indefinidamente.
# ¿Qué es un paquete y cómo instalo uno?
Un "paquete" es una colección de funciones, datos y código `R` con un propósito específico y en un formato bien definido. Hay miles de paquetes para `R` que han sido escritos por usuarios de `R`. Las personas escriben paquetes para compartir los códigos que han escrito que facilitan las tareas específicas. La OMS ha escrito un paquete para facilitar el análisis de los datos del MDS. El paquete escrito por la OMS se llama `whomds`. Se puede instalar `whomds` ejecutando el siguiente código en la consola:
```{r install-cran}
install.packages("whomds")
```
# Utilizar `whomds`
Una vez que se instala `whomds`, se puede abrir con el siguiente código:
```{r open-whomds}
library(whomds)
```
`whomds` contiene tres tipos de funciones:
* Funciones `table_*()` - producen diferentes tablas de estadísticas descriptivas
* Funciones `fig_*()` - producen diferentes figuras
* Funciones `rasch_*()` - utilizadas al realizar el Análisis Rasch
En esta sección nos centraremos en las funciones `rasch_*()`.
Hay dos conjuntos de funciones `rasch_*()` en el paquete `whomds`: un conjunto para adultos y otro para niños. La razón por la que se necesitan diferentes funciones para cada grupo es que el tipo de Análisis de Rasch realizado para cada grupo es diferente. El Análisis de Rasch realizado para adultos es sencillo; Toda la población adulta puede ser considerada en un grupo. El Análisis de Rasch para niños requiere un análisis más complicado, porque los niños de diferentes edades son muy diferentes y pueden realizar diferentes tipos de actividades. Primero describiremos el análisis de los adultos, y luego describiremos el análisis de los niños.
## Dependencias de paquetes
El paquete `whomds` depende de varios otros paquetes para funcionar correctamente. Cuando se instale `whomds`, también se instalarán todos los demás paquetes que utiliza. Asegúrate de que estos otros paquetes se instalen correctamente investigando cualquier error que surja durante la instalación.
Los paquetes adicionales son:
* `colorspace`
* `dplyr`
* `eRm`
* `ggraph`
* `ggplot2`
* `GPArotation`
* `grDevices`
* `igraph`
* `nFactors`
* `plyr`
* `polycor`
* `purrr`
* `RColorBrewer`
* `readr`
* `rlang`
* `scales`
* `srvyr`
* `stringr`
* `TAM`
* `tibble`
* `tidygraph`
* `tidyr`
* `WrightMap`
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c2_getting_started_ES.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
## ----rasch-mds-help-----------------------------------------------------------
# ?rasch_mds
## ----rasch-mds-example--------------------------------------------------------
# rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Start",
# testlet_strategy = NULL,
# recode_strategy = NULL,
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Initial run"
# )
## ----rasch-mds-testlet--------------------------------------------------------
# rasch_mds(
# ...,
# testlet_strategy = list(
# new = c("EF4", "EF6", "EF8"),
# c("EF5", "EF7")
# )
# )
## ----rasch-mds-recode---------------------------------------------------------
# rasch_mds(
# ...,
# recode_strategy = list(
# "EF1,EF2" = c(0,1,2,3,3),
# "EF3" = c(0,0,1,2,3)
# )
# )
## ----rasch-mds-drop-----------------------------------------------------------
# rasch_mds(
# ...,
# drop_vars = c("EF4", "EF7")
# )
## ----rasch-mds-split----------------------------------------------------------
# rasch_mds(
# ...,
# split_strategy = list(
# sex = c("EF1", "EF2"),
# age_cat = c("EF3")
# )
# )
## ----adult-start-example------------------------------------------------------
# start <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Start",
# testlet_strategy = NULL,
# recode_strategy = NULL,
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Initial run"
# )
## ----adult-start-LID, echo=FALSE, eval=TRUE-----------------------------------
include_graphics("Images/ExampleRasch_EF/Start/LID_plot.png")
## ----adult-start-scree, echo=FALSE, eval=TRUE---------------------------------
include_graphics("Images/ExampleRasch_EF/Start/parallel_analysis_scree.png")
## ----adult-start-PI, echo=FALSE, eval=TRUE------------------------------------
include_graphics("Images/ExampleRasch_EF/Start/PImap.png")
## ----adult-t1-example---------------------------------------------------------
# testlet1 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = NULL,
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25)"
# )
## ----adult-t1-error, echo=FALSE, eval=TRUE, message=TRUE----------------------
message("Error in tapply(1L:ncol(X01beta), mt_ind, function(xin) { :
arguments must have same length ")
## ----adult-t1r1-example-------------------------------------------------------
# testlet1_recode1 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1_Recode1",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5)),
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5"
# )
## ----adult-t1r1-PI, echo=FALSE, eval=TRUE-------------------------------------
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode1/PImap.png")
## ----adult-t1r2-example-------------------------------------------------------
# testlet1_recode2 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1_Recode2",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
# "EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,3)),
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,3"
# )
## ----adult-t1r2-PI, echo=FALSE, eval=TRUE-------------------------------------
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode2/PImap.png")
## ----adult-t1r3-example-------------------------------------------------------
# testlet1_recode3 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1_Recode3",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
# "EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,2)),
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,2"
# )
## ----adult-t1r3-PI, echo=FALSE, eval=TRUE-------------------------------------
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode3/PImap.png")
## ----adult-t1r4-example-------------------------------------------------------
# testlet1_recode4 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1_Recode4",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
# "EF1,EF2,EF3,EF4,EF5,EF7,EF8,EF9,EF10" = c(0,1,1,2,2),
# EF6 = c(0,1,1,1,2)),
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else except EF6 to 0,1,1,2,2, EF6 to 0,1,1,1,2"
# )
## ----adult-t1r4-PI, echo=FALSE, eval=TRUE-------------------------------------
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode4/PImap.png")
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c3_rasch_adults_EN.R
|
---
title: "3 - Rasch Analysis for MDS data from adults"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{3 - Rasch Analysis for MDS data from adults}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Structure
To perform Rasch Analysis for adults, only one function needs to be used: `rasch_mds()`. This is referred to as a "wrapper function." A wrapper function is a function that makes it easier to use other functions. In our case, `rasch_mds()` utilizes all the other `rasch_*()` functions to perform the analysis. These other `rasch_*()` functions used for adults are:
* `rasch_DIF()`
* `rasch_drop()`
* `rasch_factor()`
* `rasch_model()`
* `rasch_rawscore()`
* `rasch_recode()`
* `rasch_rescale()`
* `rasch_split()`
* `rasch_testlet()`
You only need to use the function `rasch_mds()`. But if you wanted to perform your analysis in a more customized way, you could work with the internal functions directly.
# Output
After each iteration of the Rasch Model, the codes above produce a variety of files that will tell you how well the data fit the assumptions of the model at this iteration. The most important files are the ones below. We will explain each in detail through our example.
* `LID_plot.pdf` - shows correlated items
* `LID_above_0.2.csv` - correlations between correlated items
* `parallel_analysis_scree.pdf` - scree plot
* `bifactor_analysis.pdf` - loadings of factors
* `PImap.pdf`- locations of persons and items, ordering of thresholds
* `item_fit.csv` - item fit
* `Targeting.csv` - reliability of model
# Arguments of `rasch_mds()`
In this section we will examine each argument of the function `rasch_mds()`. The help file for the function also describes the arguments. Help files for functions in `R` can be accessed by writing `?` before the function name, like so:
```{r rasch-mds-help}
?rasch_mds
```
Below is an example of a use of the function `rasch_mds()`:
```{r rasch-mds-example}
rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run"
)
```
The first argument is `df`. This argument is for the data. The data object should be individual survey data, with one row per individual. Here the data is stored in an object `df_adults`, which is a dataset included in the `whomds` package. To find out more about `df_adults` please look at its help file by running: `?df_adults`
The second argument is `vars_metric`, which is equal to a character vector of the column names for the items to use in Rasch Analysis. Here it is equal to `paste0("EF", 1:12)`, which is a character vector of length 12 of the column names `EF1`, `EF2`, ... `EF11`, and `EF12`.
The next argument is `vars_id`, which is the name of the column used to uniquely identify individuals. Here the ID column is called `HHID`.
The next argument is `vars_DIF`. It is equal to a character vector with the names of the columns that are used to analyze differential item functioning (DIF). DIF will be discussed in more detail in later sections. Here `vars_DIF` is equal to a character vector of length two containing the name of the columns `"sex"` and `"age_cat"`.
The next argument is `resp_opts`. This is a numeric vector with the possible response options for `vars_metric`. In this survey, the questions `EF1` to `EF12` have response options 1 to 5. So here `resp_opts` is equal to a numeric vector of length 5 with the values `1`, `2`, `3`, `4` and `5`.
The next argument is `max_NA`. This is a numeric value for the maximum number of missing values allowed for an individual to be still be considered in the analysis. Rasch Analysis can handle individuals having a few missing values, but too many will cause problems in the analysis. In general all individuals in the sample should have fewer than 15% missing values. Here `max_NA` is set to `2`, meaning individuals are allowed to have a maximum of two missing values out of the questions in `vars_metric` to still be included in the analysis.
The next argument is `print_results`, which is either `TRUE` or `FALSE`. When it is `TRUE`, files will be saved onto your computer with results from the Rasch iteration. When it is `FALSE`, files will not be saved.
The next argument is `path_parent`. This is a string with the path to the folder where the results of multiple models will be saved, assuming `print_results` is `TRUE`. The folder in `path_parent` will then contain separate folders with the names specified in `model_name` at each iteration. In the function call above, all results will be saved on the Desktop. Note that when writing paths for `R`, the slashes should all be: `/` (NOT `\`). Be sure to include a final `/` on the end of the path.
The next argument is `model_name`. This is equal to a string where you give a name of the model you are running. This name will be used as the name of the folder where all the output will be saved on your computer, if `print_results` is `TRUE`. The name you give should be short but informative. For example, you may call your first run "Start", as it is called here. If you create a testlet in your second run perhaps you can call it "Testlet1", etc. Choose whatever will be meaningful to you.
The next arguments are `testlet_strategy`, `recode_strategy`, `drop_vars` and `split_strategy`. These are arguments that control how the data is used in each iteration of the Rasch Model. Each will be discussed in more detail in later sections. Here they are all set to `NULL`, which means they are not used in the iteration of Rasch Analysis shown here.
The last argument is `comment`. This is equal to a string where you can write some free-text information about the current iteration so that when you are looking at the results later you can remember what you did and why you did it. It is better to be more detailed, because you will forget why you chose to run the model in this particular way. This comment will be saved in a file `Comment.txt`. Here the comment is just `"Initial run"`.
# Adjusting the data
Next, we will discuss the arguments that give instructions about how to adjust the data. These parts may not be entirely meaningful now, but will become more so after we go through an example.
## Making testlets
If you want to create testlets--that is, sum up items into super items in order to fix item dependence--then pass a strategy for making testlets to the argument `testlet_strategy`. `testlet_strategy` is a list with one element of the list per testlet that you want to create. Each element of the list must be a character vector of column names to use for the testlet. Optionally, you can name the elements of the list to give custom names to the new testlets. Otherwise, the new testlets will be the original column names separated by "_".
For example, imagine you wanted to make two testlets: one testlet from variables `EF4`, `EF6`, and `EF8` with a new name of `new`, and another testlet from `EF5` and `EF7`, without a new name specified. Then you would specify `testlet_strategy` as the following:
```{r rasch-mds-testlet}
rasch_mds(
...,
testlet_strategy = list(
new = c("EF4", "EF6", "EF8"),
c("EF5", "EF7")
)
)
```
## Recoding
If you want to recode response options--that is, change response options in order to create stochastic ordering--then pass a strategy for the recoding to the argument `recode_strategy`. `recode_strategy` takes the form of a named list, with one element of the list per recode strategy. The names of the list are the groups of column names to use for each recoding strategy, separated only by ",". Each element of the list is a numeric vector giving the new response options to map the variables to.
For example, if you wanted to collapse the last two response options of the variables `EF1` and `EF2`, and collapse the first two response options of `EF3`, then you would set `recode_strategy` as the following:
```{r rasch-mds-recode}
rasch_mds(
...,
recode_strategy = list(
"EF1,EF2" = c(0,1,2,3,3),
"EF3" = c(0,0,1,2,3)
)
)
```
## Dropping variables
If you want to drop any items from your analysis--perhaps in the event of extremely poor fit--then set `drop_vars` as a character vector of the column names to drop from the analysis.
For example, if the items `EF4` and `EF7` were extremely poorly fitting items, then they could be dropped from the analysis by setting `drop_vars` as the following:
```{r rasch-mds-drop}
rasch_mds(
...,
drop_vars = c("EF4", "EF7")
)
```
## Splitting
If you want to split items by subgroups--perhaps in the event of high differential item functioning (DIF)--then you give the instructions for your split strategy in the argument `split_strategy`.
Splitting items entails taking a single item and separating it into two or more items for different groups. For example, if we wanted to split an item `var` by sex, then we would create two items: `var_Male` and `var_Female`. `var_Male` would be equivalent to `var` for all respondents that are men, and `NA` for the respondents that are women. `var_Female` would be equivalent to `var` for all respondents that are women, and `NA` for the respondents that are men.
`split_strategy` takes the form of a named list. There is one element of the list per variable to split by. Each element of the list must be a character vector of column names to split. The names of the list are the variables to split each group of variables by.
For example, if we wanted to split the variables `EF1` and `EF2` by `sex`, and split `EF3` by age category `age_cat`, then we would set `split_strategy` to be the following:
```{r rasch-mds-split}
rasch_mds(
...,
split_strategy = list(
sex = c("EF1", "EF2"),
age_cat = c("EF3")
)
)
```
However, because we expect a certain amount of DIF when measuring disability--especially by sex and age--we rarely use this option. To not perform any splitting, leave `split_strategy` as its default value of `NULL.`
# Example
Below we will be creating a metric using the sample data `df_adults` using the environmental factors (EF) questions from the questionnaire. These are questions `EF1` to `EF12`.
## Start
We will start by trying to run the model without performing any adjustments on our data. To run this model, run a command that is similar to this:
```{r adult-start-example}
start <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run"
)
```
The code you run may not be exactly the same, because for instance the directory you use for `path_parent` will be specific to your machine, and you may choose a different `model_name` and `comment` for your model.
By running this command, in addition to printing results to your machine (because `print_results` is `TRUE`), you are also saving some output to an object in `R`'s global environment called `start`. This object is a list with three elements: one named `df`, one named `vars_metric`, and one named `df_results`. `df` contains the data with the transformed variables used to create the score and the rescaled scores. `vars_metric` is a character vector of the names of the `vars_metric` after transforming the variables. `df_results` is a data frame with one row and a column for each of the main statistics for assessing the assumptions of the Rasch Model. `df_results` from multiple models can be merged in order to create a data frame that allows you to quickly compare different models.
It is not necessary to save the output of `rasch_mds()` to an object in the global environment, but it makes it easier to manipulate the resulting output in order to determine what adjustments to make to your data in the next iteration.
After running this command, various files will be saved to the folder that you specified. Go to the `path_parent` folder, and you will see a new folder with the name you specified in `model_name`. Inside that folder, there will be many files. We will focus on the most important ones. Please read again Section \@ref(repair) to review how the different Rasch Model assumptions affect one another and to understand why we will check the important files in this particular order.
First we will check the local item dependence of the items. We can check this by looking at the files `LID_plot.pdf` and `LID_above_0.2.csv`. `LID_above_0.2.csv` gives the correlations of the residuals that are above 0.2, and `LID_plot.pdf` is a visualization of these correlations. From these files, we can see that the items `EF11` and `EF12` are correlated. The value of the correlation is approximately 0.47. These two items have to do with how facilitating or hindering work (`EF11`) and school (`EF12`) are. Conceptually, it makes sense that people's answers to these two questions are related. We will take care of this correlation at the next iteration of the model.
```{r adult-start-LID, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/LID_plot.png")
```
Next we will investigate the unidimensionality of the model by analyzing the file `parallel_analysis_scree.pdf`. This is what's known as a "scree plot." A scree plot shows the eigenvalues for our model, and indicates how many underlying dimensions we have in our questionnaire. With this scree plot, we hope to see a very sharp decline after the first eigenvalue on the left, and that the second eigenvalue falls below the green line of the "Parallel Analysis". This would mean that we have one underlying dimensions that is very strong in our data, and any further dimensions that are computed have very little influence on the model. In our graph, we do see a very sharp decline after the first eigenvalue, and the green line crosses the black line after the second factor. This is sufficient to confirm unidimensionality for the model.
```{r adult-start-scree, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/parallel_analysis_scree.png")
```
Another important file we can examine is the `PImap.pdf`. This is the "Person-Item Map", and it shows people and items on the same continuum. The horizontal axis on the bottom of the figure is this continuum, labeled as the "latent dimension". The top of the figure is labeled the "person parameter distribution". This is the distribution of people's scores on the continuum. It can show you if, for instance, you have more people on one end of the scale or another.
```{r adult-start-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/PImap.png")
```
The largest part of this figure shows where the thresholds for each item are located on the continuum. The thresholds are labeled with numbers: the first threshold is labeled "1", the second is labeled "2", and so on. The black dot is the average of the locations of all these thresholds. The stars on the right side of the figure indicate whether or not the thresholds are out of order. For instance, you can see for `EF1`, the thresholds are ordered 2, 4, 1, 3 which is clearly out of order. In fact, in this case, all of the items have thresholds out of order. This is likely something we will need to take care of later, but first we will take care of the item dependence.
Another important file we can analyze is `item_fit.csv`. This file gives the fit statistics for each item. Two fit statistics used here are "outfit" and "infit", given in the columns `i.outfitMSQ` and `i.infitMSQ`. They are both similar, but outfit is more sensitive to outliers. In general we hope that these figures are as close to 1 as possible. If they are below 1, then it indicates the item is overfitting. "Overfit" refers to the situation when items fit "too closely" to the model. If these statistics are greater than 1, then they indicate the items are underfitting. "Underfit" refers to the situation when items do not fit the model well. Underfitting is more serious than overfitting. We hope in general that items' infit and outfit are between 0.5 and 1.5. If they are less than 0.5, reliability measures for the model may be misleadingly high, but the scores can still be used. If they are between 1.5 and 2.0, this is a warning sign that the items may be causing problems and you could begin to consider adjusting the data to improve the fit. If they are greater than 2.0, the scores calculated may be significantly distorted and action should be taken to adjust the data to improve fit.
In this case, all of the items have infit and outfit statistics between 0.5 and 1.5, which is good.
To analyze overall model fit, we can open the file `Targeting.csv`. This file gives the mean and standard deviation of the person abilities and of the item difficulties. It also gives the "person separation index", or PSI, which is a measure of reliability for the model. We hope this value is as close to 1 as possible. It is generally acceptable if it is this figure is above 0.7, though we hope to get values as high as 0.8 or 0.9. For our model here, our PSI is 0.82, which is very good.
## Testlet1
With our next iteration of the model, we will try to address the high item dependence between items `EF11` and `EF12`. We will do this by creating a testlet between these two items. We do this by changing the argument `testlet_stratey` as shown below. We have given the new testlet the name `workschool`, but you could name it whatever you wished.
```{r adult-t1-example}
testlet1 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25)"
)
```
After running this model, we get an error:
```{r adult-t1-error, echo=FALSE, eval=TRUE, message=TRUE}
message("Error in tapply(1L:ncol(X01beta), mt_ind, function(xin) { :
arguments must have same length ")
```
This error is a bit strange looking. But sometimes errors like this will arise because of too many NAs in the data or if there are not enough people endorsing all possible response options. Let's look at the file `response_freq.csv` in order to see how the response options are distributed. We can see in this file that there are many endorsements for all response options for all questions except for our new testlet `workschool`, which only has 1 person with an answer of 6, and no one with the possible answers of 5, 7 or 8. Perhaps this is what is causing the problem.
### More on recoding
First let's discuss recoding in a bit more detail.
Each question with `n` response options will have `n-1` thresholds. The first threshold (labeled with a "1" in the person-item map) is the point between the first and second response option where a respondent is equally likely to choose either of these response options; the second threshold (labeled with a "2" in the person-item map) is the point between the second and third response option where a respondent is equally likely to choose either of these response options; and so on.
We want our thresholds in the person-item map to be in the right order: 1, 2, 3, 4 and so on. Disordered thresholds indicate a problem with our items. For example, if the thresholds are listed in the order 1, 2, 4, 3, then the data are telling us that someone is more likely to surpass the 4th threshold before the 3rd threshold, which does not make sense. We recode the response options in order create fewer thresholds so that it is easier for them to be in order.
The functions to perform Rasch Analysis shift our response options so that they start with 0. This is done because the functions for performing the analysis require it. For example, our survey has questions that have response options ranging from 1 to 5, but internally the function shifts these response options so they range from 0 to 4. Consequently, it becomes slightly more straightforward to interpret which response options need to be recoded directly from the labels of the thresholds. For example, if an item is disordered in the pattern 1, 2, 4, 3, this means that thresholds 4 and 3 are out of order. This also means that we can recode the transformed response options 4 and 3 in order to collapse these thresholds.
When we want to recode an item, we supply the function with instructions on what to map the response options to. For example, let's say an item `var` has disordered thresholds in the pattern 1, 2, 4, 3. We now want to collapse the 4th and the 3rd threshold so that the item becomes ordered. `var` has response options ranging from 0 to 4 (after being shifted from the original 1 to 5), so we want to combine the response options 3 and 4 for the item in order to collapse these two thresholds. We do this by telling the function to map the current response options of 0, 1, 2, 3, 4 to 0, 1, 2, 3, 3. This means all responses of "4" are now recoded to be "3". Now we will only have 4 different response options, which means we will have 3 different thresholds, which will now hopefully be in the proper order.
This will become clearer as we work through the example.
## Testlet1_Recode1
At the next iteration, we will try to recode the response options of our testlet so that the model is able to run.
We will run the command like below:
```{r adult-t1r1-example}
testlet1_recode1 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode1",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5"
)
```
The difference between the Testlet1 model and this model is that we have now added a recoding strategy. We will recode the response options of the testlet `workschool` to 0,1,2,3,4,5,5,5,5. This means all response options will stay the same, except the response options 5 through 8 are combined.
After we run the command, we see the model is able to be calculated as normal.
First we check `LID_plot.pdf` to see if we have been able to remove the item correlation. In this file, we see the message "No LID found", which means our testlet strategy was effective!
Next, we check the scree plot in the file `parallel_analysis_scree.pdf` to make sure our unidimensionality was maintained. Indeed, it looks very similar to the initial model, which is what we hope for.
Next we check the person-item map in `PImap.pdf`. We can see in this file all the items are still disordered, so this is likely the next thing we will have to take care of in the next iteration of the model.
```{r adult-t1r1-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode1/PImap.png")
```
We finally will check the item fit and the overall model fit in `item_fit.csv` and `Targeting.csv`, respectively. We can see these values are all still good--every item still has infit and outfit statistics between 0.5 and 1.5, and the PSI is still 0.82.
## Testlet1_Recode2
Next we will try recoding items in order to create ordered thresholds. We are most worried about having the single items (everything that is not a testlet) ordered.
There are various ways you can choose the recoding strategy. In general you want to do the minimum amount of recoding necessary to acheive ordered thresholds. We will try first to collapse the first two thresholds for all items that are not the testlet. We will see which items this works for, and try a new strategy at the next iteration for the items where it did not work.
```{r adult-t1r2-example}
testlet1_recode2 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode2",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,3)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,3"
)
```
We can see in the new person-item map that this strategy did not work for any of the items. So we will try a new strategy at the next iteration.
```{r adult-t1r2-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode2/PImap.png")
```
We can also check the other files to see if any other Rasch Model assumptions have now been violated with this recoding strategy. But because we are changing our strategy completely at the next iteration, it is not necessary to pay too much attention to the other files for this iteration.
## Testlet1_Recode3
From the person-item map for the Start model, we can see our items are disordered in a bit of a complicated way: many items have thresholds in order 2, 4, 1, 3 or in order 2, 3, 4, 1. Usually if an item has disordered thresholds in a fairly uncomplicated pattern (for example, 1, 2, 4, 3 or 2, 1, 3, 4) then then the recoding strategy is straightforward. For example, with disordering of 1, 2, 4, 3 it is clear that the respone options 3 and 4 should be collapsed. With disordering of 2, 1, 3, 4 then the response options of 1 and 2 should be collapsed.
In our case, the disordering is fairly complicated so the recoding strategy is less straightforward and will likely have to be more extreme. At this iteration, we will try collapsing two sets of response options: we will collapse 1 with 2 and 3 with 4, as shown below.
```{r adult-t1r3-example}
testlet1_recode3 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode3",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,2)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,2"
)
```
We can see with this recoding strategy that the thresholds are now ordered for most of the items! The only item it did not work for is `EF6`, which we will have to try a different strategy for at the next iteration.
```{r adult-t1r3-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode3/PImap.png")
```
We made progress on our threshold disordering, but we need to make sure that the other Rasch Model assumptions have not now been violated with this new strategy. We check `LID_plot.pdf` and see we still have achieved item independence. We also check the scree plot in `parallel_analysis_scree.pdf` to see if we still have unidimensionality. Finally, we also check `item_fit.csv` and `Targeting.csv` and see that the values are still acceptable in these files as well. So we will proceed with an altered recoding strategy in the next iteration.
## Testlet1_Recode4
We still have two items that are disordered: `EF6` and `workschool`. We do not generally worry about testlets being disordered because they are not items originally included in the questionnaire. We could recode `workschool` if its item fit was very poor, but in our model it maintains good item fit based on the infit and outfit statistics, so we will not recode it.
Therefore at this iteration we will just try to solve the disordering of `EF6`. We will try collapsing the middle three response options, as shown below.
```{r adult-t1r4-example}
testlet1_recode4 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode4",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF7,EF8,EF9,EF10" = c(0,1,1,2,2),
EF6 = c(0,1,1,1,2)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else except EF6 to 0,1,1,2,2, EF6 to 0,1,1,1,2"
)
```
After running this model, we see the disordering for `EF6` has been resolved! All single items now have ordered thresholds!
```{r adult-t1r4-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode4/PImap.png")
```
We will also check the other files to make sure our other Rasch Model assumptions have been maintained. We check `LID_plot.pdf` and see we still have achieved item independence. We also check the scree plot in `parallel_analysis_scree.pdf` to see if we still have unidimensionality. Finally, we also check `item_fit.csv` and `Targeting.csv` and see that the values are still acceptable in these files as well.
All of our Rasch Model assumptions have been reasonably attained, so this means we can stop! We have finished our Rasch Analysis for this set of questions. The data with the scores is in the file `Data_final.csv`. We will discuss what to do with these scores in later sections.
# Best practices
Go to the [Best Practices in Rasch Analysis](c5_best_practices_EN.html) vignette to read more about general rules to follow.
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c3_rasch_adults_EN.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
## ----rasch-mds-help-----------------------------------------------------------
# ?rasch_mds
## ----rasch-mds-example--------------------------------------------------------
# rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Start",
# testlet_strategy = NULL,
# recode_strategy = NULL,
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Initial run"
# )
## ----rasch-mds-testlet--------------------------------------------------------
# rasch_mds(
# ...,
# testlet_strategy = list(
# new = c("EF4", "EF6", "EF8"),
# c("EF5", "EF7")
# )
# )
## ----rasch-mds-recode---------------------------------------------------------
# rasch_mds(
# ...,
# recode_strategy = list(
# "EF1,EF2" = c(0,1,2,3,3),
# "EF3" = c(0,0,1,2,3)
# )
# )
## ----rasch-mds-drop-----------------------------------------------------------
# rasch_mds(
# ...,
# drop_vars = c("EF4", "EF7")
# )
## ----rasch-mds-split----------------------------------------------------------
# rasch_mds(
# ...,
# split_strategy = list(
# sex = c("EF1", "EF2"),
# age_cat = c("EF3")
# )
# )
## ----adult-start-example------------------------------------------------------
# start <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Start",
# testlet_strategy = NULL,
# recode_strategy = NULL,
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Initial run"
# )
## ----adult-start-LID, echo=FALSE, eval=TRUE-----------------------------------
include_graphics("Images/ExampleRasch_EF/Start/LID_plot.png")
## ----adult-start-scree, echo=FALSE, eval=TRUE---------------------------------
include_graphics("Images/ExampleRasch_EF/Start/parallel_analysis_scree.png")
## ----adult-start-PI, echo=FALSE, eval=TRUE------------------------------------
include_graphics("Images/ExampleRasch_EF/Start/PImap.png")
## ----adult-t1-example---------------------------------------------------------
# testlet1 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = NULL,
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25)"
# )
## ----adult-t1-error, echo=FALSE, eval=TRUE, message=TRUE----------------------
message("Error in tapply(1L:ncol(X01beta), mt_ind, function(xin) { :
arguments must have same length ")
## ----adult-t1r1-example-------------------------------------------------------
# testlet1_recode1 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1_Recode1",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5)),
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5"
# )
## ----adult-t1r1-PI, echo=FALSE, eval=TRUE-------------------------------------
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode1/PImap.png")
## ----adult-t1r2-example-------------------------------------------------------
# testlet1_recode2 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1_Recode2",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
# "EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,3)),
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,3"
# )
## ----adult-t1r2-PI, echo=FALSE, eval=TRUE-------------------------------------
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode2/PImap.png")
## ----adult-t1r3-example-------------------------------------------------------
# testlet1_recode3 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1_Recode3",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
# "EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,2)),
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,2"
# )
## ----adult-t1r3-PI, echo=FALSE, eval=TRUE-------------------------------------
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode3/PImap.png")
## ----adult-t1r4-example-------------------------------------------------------
# testlet1_recode4 <- rasch_mds(
# df = df_adults,
# vars_metric = paste0("EF", 1:12),
# vars_id = "HHID",
# vars_DIF = c("sex", "age_cat"),
# resp_opts = 1:5,
# max_NA = 2,
# print_results = TRUE,
# path_parent = "/Users/lindsaylee/Desktop/",
# model_name = "Testlet1_Recode4",
# testlet_strategy = list(workschool = c("EF11", "EF12")),
# recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
# "EF1,EF2,EF3,EF4,EF5,EF7,EF8,EF9,EF10" = c(0,1,1,2,2),
# EF6 = c(0,1,1,1,2)),
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else except EF6 to 0,1,1,2,2, EF6 to 0,1,1,1,2"
# )
## ----adult-t1r4-PI, echo=FALSE, eval=TRUE-------------------------------------
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode4/PImap.png")
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c3_rasch_adults_ES.R
|
---
title: "3 - Análisis Rasch con los datos de adultos de MDS"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{3 - Análisis Rasch con los datos de adultos de MDS}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Estructura
Para realizar el Análisis Rasch para adultos, solo se necesita usar una función: `rasch_mds()`. Esto se conoce como una "función de envoltura" (_wrapper function_). Una función de envoltura es una función que facilita el uso de otras funciones. En nuestro caso, `rasch_mds()` utiliza todas las otras funciones `rasch_*()` para realizar el análisis. Estas otras funciones `rasch_*()` usadas para adultos son:
* `rasch_DIF()`
* `rasch_drop()`
* `rasch_factor()`
* `rasch_model()`
* `rasch_rawscore()`
* `rasch_recode()`
* `rasch_rescale()`
* `rasch_split()`
* `rasch_testlet()`
Solo necesitas usar la función `rasch_mds()`. Pero si desea realizar su análisis de una manera más personalizada, puede trabajar directamente con las funciones internas.
# Salida
Después de cada iteración del Modelo Rasch, los códigos anteriores producen una variedad de archivos que le dirán qué tan bien los datos se ajustan a las suposiciones del modelo en esta iteración. Los archivos más importantes son los de abajo. Explicaremos cada uno en detalle a través de nuestro ejemplo.
* `LID_plot.pdf` - muestra elementos correlacionados
* `LID_above_0.2.csv` - correlaciones entre elementos correlacionados
* `parallel_analysis_scree.pdf` - gráfico de scree
* `bifactor_analysis.pdf` - cargas de factores
* `PImap.pdf`- ubicaciones de personas y ítems, ordenamiento de umbrales
* `item_fit.xlsx` - ajuste de ítems
* `Targetting.csv` - fiabilidad del modelo
# Argumentos de `rasch_mds()`
En esta sección examinaremos cada argumento de la función `rasch_mds()`. El archivo de ayuda para la función también describe los argumentos. Se puede acceder a los archivos de ayuda para las funciones en `R` escribiendo `?` antes del nombre de la función, de esta manera:
```{r rasch-mds-help}
?rasch_mds
```
A continuación se muestra un ejemplo de uso de la función `rasch_mds()`:
```{r rasch-mds-example}
rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run"
)
```
El primer argumento es `df`. Este argumento es para los datos. El objeto de datos debe ser datos de encuestas individuales, con una fila por persona. Aquí los datos se almacenan en un objeto `df_adults`, que es un base de datos incluido en el paquete` whomds`. Para obtener más información sobre `df_adults`, consulta su archivo de ayuda ejecutando:`?df_adults`
El segundo argumento es `vars_metric`, que es igual a un vector de caracteres de los nombres de columna para los elementos a usar en el Análisis de Rasch. Aquí es igual a `paste0("EF", 1:12)`, que es un vector de caracteres de longitud 12 de los nombres de columna `EF1`, `EF2`, ... `EF11` y `EF12`.
El siguiente argumento es `vars_id`, que es el nombre de la columna utilizada para identificar de forma única a los individuos. Aquí la columna de ID se llama `HHID`.
El siguiente argumento es `vars_DIF`. Es igual a un vector de caracteres con los nombres de las columnas que se utilizan para analizar el funcionamiento diferencial de elementos (DIF). DIF se tratará con más detalle en las secciones posteriores. Aquí `vars_DIF` es igual a un vector de caracteres de longitud dos que contiene el nombre de las columnas `"sex"` y `"age_cat"`.
El siguiente argumento es `resp_opts`. Este es un vector numérico con las posibles opciones de respuesta para `vars_metric`. En esta encuesta, las preguntas `EF1` a `EF12` tienen las opciones de respuesta 1 a 5. Entonces, `resp_opts` es igual a un vector numérico de longitud 5 con los valores `1`, `2`,` 3`, `4` y `5`.
El siguiente argumento es `max_NA`. Este es un valor numérico para el número máximo de valores faltantes permitidos para que una persona aún se tenga en cuenta en el análisis. El Análisis de Rasch puede manejar a personas que tienen algunos valores faltantes, pero demasiados causarán problemas en el análisis. En general, todos los individuos en la muestra deben tener menos del 15% de valores faltantes. Aquí `max_NA` es `2`, lo que significa que se permite que los individuos tengan un máximo de dos valores faltantes de las preguntas en `vars_metric` para que aún se incluyan en el análisis.
El siguiente argumento es `print_results`, que es `TRUE` o `FALSE`. Cuando es `TRUE`, los archivos se guardarán en su computadora con los resultados de la iteración Rasch. Cuando es `FALSE`, los archivos no se guardarán.
El siguiente argumento es `path_parent`. Esta es una cadena con la ruta a la carpeta donde se guardarán los resultados de múltiples modelos, asumiendo que `print_results` es `TRUE`. La carpeta en `path_parent` contendrá carpetas separadas con los nombres especificados en `model_name` en cada iteración. En la ejecución de la función anterior, todos los resultados se guardarán en el Desktop. Ten en cuenta que al escribir rutas para `R`, todas las barras deberían ser: `/ `(NO `\`). Asegúrate de incluir un `/` final en el final de la ruta.
El siguiente argumento es `model_name`. Esto es igual a una cadena donde le das un nombre del modelo que estás ejecutando. Este nombre se usará como el nombre de la carpeta donde se guardará toda la salida en su computadora, si `print_results` es `TRUE`. El nombre que le des debe ser corto pero informativo. Por ejemplo, puede llamar a su primera ejecución "Start", como se llama aquí. Si creas un testlet en su segunda ejecución, quizás puedas llamarlo "Testlet1", etc. Elije lo que sea significativo para tí.
Los siguientes argumentos son `testlet_strategy`, `recode_strategy`, `drop_vars` y `split_strategy`. Estos son argumentos que controlan cómo se usan los datos en cada iteración del Modelo Rasch. Cada uno será discutido con más detalle en secciones posteriores. Aquí están todos configurados en `NULL`, lo que significa que no se usan en la iteración del Análisis Rasch que se muestra aquí.
El último argumento es `comment`. Esto es igual a una cadena en la que puedes escribir cierta información de texto libre sobre la iteración actual para que cuando veas los resultados más adelante puedas recordar lo que hiciste y por qué lo hiciste. Es mejor ser más detallado, porque olvidarás por qué eligiste ejecutar el modelo de esta manera en particular. Este comentario se guardará en un archivo `Comment.txt`. Aquí el comentario es solo `"Initial run"`.
# Ajustar los datos
A continuación, discutiremos los argumentos que dan instrucciones sobre cómo ajustar los datos. Es posible que estas partes no sean del todo significativas ahora, pero lo serán aún más después de que pasemos por un ejemplo.
## Crear testlets
Si deseas crear testlets, es decir, sumar los ítems en súper-ítems para corregir la dependencia de los ítems, luego pasa una estrategia para hacer testlets al argumento `testlet_strategy`. `testlet_strategy` es una lista con un elemento de la lista por testlet que deseas crear. Cada elemento de la lista debe ser un vector de caracteres de los nombres de columna para usar para el testlet. Opcionalmente, puede nombrar los elementos de la lista para dar nombres personalizados a los nuevos testlets. Sin nombres especificados, los nuevos testlets serán los nombres de columna originales separados por "_".
Por ejemplo, imagine que desea hacer dos testlets: un testlet de las variables `EF4`, `EF6` y `EF8` con un nuevo nombre de `new`, y otro testlet de `EF5` y `EF7`, sin un nuevo nombre especificado. Entonces deberías especificar `testlet_strategy` como lo siguiente:
```{r rasch-mds-testlet}
rasch_mds(
...,
testlet_strategy = list(
new = c("EF4", "EF6", "EF8"),
c("EF5", "EF7")
)
)
```
## Recodificación
Si deseas recodificar las opciones de respuesta, es decir, cambiar las opciones de respuesta para crear un ordenamiento estocástico, entonces pasa una estrategia para la recodificación al argumento `recode_strategy`. `recode_strategy` toma la forma de una lista nombrada, con un elemento de la lista por estrategia de recode. Los nombres de la lista son los grupos de nombres de columna que se deben usar para cada estrategia de recodificación, separados solo por ",". Cada elemento de la lista es un vector numérico que proporciona las nuevas opciones de respuesta para asignar las variables.
Por ejemplo, si desea combinar las dos últimas opciones de respuesta de las variables `EF1` y `EF2`, y combinar las dos primeras opciones de respuesta de `EF3`, entonces establecería `recode_strategy` como lo siguiente:
```{r rasch-mds-recode}
rasch_mds(
...,
recode_strategy = list(
"EF1,EF2" = c(0,1,2,3,3),
"EF3" = c(0,0,1,2,3)
)
)
```
## Eliminar variables
Si deseas eliminar cualquier ítem de tu análisis, tal vez en el caso de un ajuste extremadamente deficiente, configura `drop_vars` como un vector de caracteres de los nombres de columna para que se eliminen del análisis.
Por ejemplo, si los ítems `EF4` y `EF7` eran ítems extremadamente mal ajustados, entonces podrían eliminarse del análisis especificando `drop_vars` como lo siguiente:
```{r rasch-mds-drop}
rasch_mds(
...,
drop_vars = c("EF4", "EF7")
)
```
## Dividir
Si deseas dividir los ítems por subgrupos, tal vez en el caso de funcionamiento diferencial de ítems (DIF) alto, a continuación, das las instrucciones para su estrategia de división en el argumento `split_strategy`.
La división de ítems implica tomar un solo ítem y separarlo en dos o más ítems para diferentes grupos. Por ejemplo, si quisiéramos dividir un ítem `var` por sexo, crearíamos dos ítems:` var_Male` y `var_Female`. `var_Male` sería equivalente a `var` para todos los encuestados que son hombres, y `NA` para los encuestados que son mujeres. `var_Female` sería equivalente a `var` para todos los encuestados que son mujeres, y `NA` para los encuestados que son hombres.
`split_strategy` toma la forma de una lista nombrada. Hay un elemento de la lista por variable para la que divides. Cada elemento de la lista debe ser un vector de caracteres de los nombres de columna para dividir. Los nombres de la lista son las variables para las que divides cada grupo de variables.
Por ejemplo, si quisiéramos dividir las variables `EF1` y `EF2` por `sex`, y dividir `EF3` por la categoría de edad `age_cat`, entonces especificaríamos `split_strategy` como la siguiente:
```{r rasch-mds-split}
rasch_mds(
...,
split_strategy = list(
sex = c("EF1", "EF2"),
age_cat = c("EF3")
)
)
```
Sin embargo, debido a que esperamos una cierta cantidad de DIF al medir la discapacidad, especialmente por sexo y edad, rara vez usamos esta opción. Para no realizar ninguna división, deje `split_strategy` como su valor predeterminado de `NULL`.
# Ejemplo
A continuación, crearemos una métrica utilizando los datos de muestra `df_adults` utilizando las preguntas de factores ambientales (EF, por sus siglas en inglés) del cuestionario. Estas son las preguntas `EF1` a `EF12`.
## Start
Comenzaremos intentando ejecutar el modelo sin realizar ningún ajuste en nuestros datos. Para ejecutar este modelo, ejecuta un comando que sea similar a este:
```{r adult-start-example}
start <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run"
)
```
Es posible que el código que ejecutas no sea exactamente el mismo, porque, por ejemplo, el directorio que usas para `path_parent` será específico para tu máquina, y puedes elegir un `model_name` y `comment` diferentes para tu modelo.
Al ejecutar este comando, se imprime los resultados en tu máquina (porque `print_results` es `TRUE`), también está guardando algo de salida en un objeto en el entorno global de `R` llamado `start`. Este objeto es una lista con tres elementos: uno llamado `df`, uno llamado `vars_metric` y uno llamado `df_results`. `df` contiene los datos con las variables transformadas utilizadas para crear la puntuación y las puntuaciones redimensionadas. `vars_metric` es un vector de caracteres de los nombres de `vars_metric` después de transformar las variables. `df_results` es un marco de datos con una fila y una columna para cada una de las estadísticas principales para evaluar las suposiciones del modelo de Rasch. `df_results` de múltiples modelos se pueden combinar para crear un marco de datos que le permita comparar rápidamente diferentes modelos.
No es necesario guardar la salida de `rasch_mds()` en un objeto en el entorno global, pero facilita la manipulación de la salida resultante para determinar qué ajustes hacer a tus datos en la siguiente iteración.
Después de ejecutar este comando, se guardarán varios archivos en la carpeta que especificó. Va a la carpeta `path_parent`, y verás una nueva carpeta con el nombre que especificó en `model_name`. Dentro de esa carpeta, habrá muchos archivos. Nos centraremos en los más importantes. Lee nuevamente la Sección \@ref(reparación) para ver cómo los diferentes suposiciones del Modelo Rasch se afectan entre sí y para comprender por qué revisaremos los archivos importantes en este orden particular.
Primero revisaremos la dependencia local del artículo de los artículos. Podemos verificar esto mirando los archivos `LID_plot.pdf` y` LID_above_0.2.csv`. `LID_above_0.2.csv` da las correlaciones de los residuos que están por encima de 0.2, y `LID_plot.pdf` es una visualización de estas correlaciones. De estos archivos, podemos ver que los elementos `EF11` y `EF12` están correlacionados. El valor de la correlación es aproximadamente 0.47. Estos dos elementos tienen que ver con la forma en que se facilita o dificulta el trabajo (`EF11`) y la escuela (`EF12`). Conceptualmente, tiene sentido que las respuestas de las personas a estas dos preguntas estén relacionadas. Nos ocuparemos de esta correlación en la próxima iteración del modelo.
```{r adult-start-LID, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/LID_plot.png")
```
A continuación, investigaremos la unidimensionalidad del modelo analizando el archivo `parallel_analysis_scree.pdf`. Esto es lo que se conoce como una "gráfico scree". Un gráfico scree muestra los valores propios (_eigenvalues_) de nuestro modelo e indica cuántas dimensiones subyacentes tenemos en nuestro cuestionario. Con este gráfico, esperamos ver una disminución muy marcada después del primer valor propio a la izquierda, y que el segundo valor propio caiga por debajo de la línea verde del _"Parallel Analysis"_. Esto significaría que tenemos una dimensión subyacente que es muy sólida en nuestros datos, y cualquier otra dimensión que se calcule tendrá muy poca influencia en el modelo. En nuestro gráfico, vemos una disminución muy marcada después del primer valor propio, y la línea verde cruza la línea negra después del segundo factor. Esto es suficiente para confirmar la unidimensionalidad para el modelo.
```{r adult-start-scree, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/parallel_analysis_scree.png")
```
Otro archivo importante que podemos examinar es el `PImap.pdf`. Este es el "Mapa persona-ítem", y muestra personas y ítems en el mismo continuo. El eje horizontal en la parte inferior de la figura es este continuo, etiquetado como la "dimensión latente". La parte superior de la figura está etiquetada como "distribución de parámetros de persona". Esta es la distribución de las puntuaciones de las personas en el continuo. Puede mostrarle si, por ejemplo, tiene más personas en un extremo de la escala u otro.
```{r adult-start-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/PImap.png")
```
La parte más grande de esta figura muestra dónde se ubican los umbrales para cada elemento en el continuo. Los umbrales están etiquetados con números: el primer umbral está etiquetado como "1", el segundo está etiquetado como "2", y así sucesivamente. El punto negro es el promedio de las ubicaciones de todos estos umbrales. Las estrellas en el lado derecho de la figura indican si los umbrales están o no fuera de orden. Por ejemplo, puedes ver para `EF1`, los umbrales están ordenados 2, 4, 1, 3 que están claramente fuera de orden. De hecho, en este caso, todos los elementos tienen umbrales fuera de orden. Es probable que esto sea algo de lo que tengamos que ocuparnos más adelante, pero primero nos encargaremos de la dependencia del artículo.
Otro archivo importante que podemos analizar es `item_fit.csv`. Este archivo da las estadísticas de ajuste para cada elemento. Las dos estadísticas de ajuste utilizadas aquí son _"outfit"_ e _"infit"_, que se muestran en las columnas `i.outfitMSQ` e `i.infitMSQ`. Ambos son similares, pero el outfit es más sensible a los valores atípicos. En general, esperamos que estas cifras estén lo más cerca posible de 1. Si están por debajo de 1, entonces indica que el ítem está _"overfitting"_. _"Overfit"_ se refiere a la situación cuando los ítems se ajustan "demasiado cerca" al modelo. Si estas estadísticas son mayores que 1, entonces indican que los ítems son _"underfitting"_. _"Underfit"_ se refiere a la situación cuando los ítems no se ajustan bien al modelo. _Underfit_ es más grave que _overfit_. Esperamos en general que el _infit_ y el _outfit_ de los artículos estén entre 0.5 y 1.5. Si son menos de 0.5, las medidas de fiabilidad para el modelo pueden ser engañosamente altas, pero aún se pueden usar las puntuaciones. Si están entre 1.5 y 2.0, esta es una señal de advertencia de que los ítems pueden estar causando problemas y usted podría comenzar a considerar ajustar los datos para mejorar el ajuste. Si son mayores que 2.0, las puntuaciones calculadas pueden estar significativamente distorsionadas y se deben tomar medidas para ajustar los datos para mejorar el ajuste.
En este caso, todos los artículos tienen estadísticas infit y outfit entre 0.5 y 1.5, lo que es bueno.
Para analizar el ajuste global del modelo, podemos abrir el archivo `Targeting.csv`. Este archivo proporciona la media y la desviación estándar de las capacidades de la persona y de las dificultades del ítems. También proporciona el "índice de separación de personas" o PSI por sus siglas en inglés, que es una medida de fiabilidad para el modelo. Esperamos que este valor sea lo más cercano posible a 1. En general, es aceptable si esta cifra está por encima de 0.7, aunque esperamos obtener valores tan altos como 0.8 o 0.9. Para nuestro modelo aquí, nuestro PSI es 0.82, lo cual es muy bueno.
## Testlet1
Con nuestra próxima iteración del modelo, intentaremos abordar la alta dependencia de elementos entre los elementos `EF11` y `EF12`. Haremos esto creando un testlet entre estos dos elementos. Hacemos esto cambiando el argumento `testlet_stratey` como se muestra a continuación. Le hemos dado al nuevo testlet el nombre de `workschool`, pero puedes nombrarlo como desees.
```{r adult-t1-example}
testlet1 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25)"
)
```
Después de ejecutar este modelo, obtenemos un error:
```{r adult-t1-error, echo=FALSE, eval=TRUE, message=TRUE}
message("Error in tapply(1L:ncol(X01beta), mt_ind, function(xin) { :
arguments must have same length ")
```
Este error es un poco extraño. Pero a veces surgen errores como este a causa de demasiadas `NA` en los datos o si no hay suficientes personas que apoyen todas las opciones de respuesta posibles. Veamos el archivo `response_freq.csv` para ver cómo se distribuyen las opciones de respuesta. Podemos ver en este archivo que hay muchos respaldos para todas las opciones de respuesta para todas las preguntas excepto para nuestro nuevo testlet `workschool`, que solo tiene 1 persona con una respuesta de 6, y nadie con las repuestas posibles de 5, 7 o 8. Quizás esto es lo que está causando el problema.
### Más sobre la recodificación
Primero vamos a discutir la recodificación con un poco más de detalle.
Cada pregunta con `n` opciones de respuesta tendrá `n-1` umbrales. El primer umbral (etiquetado con un "1" en el mapa persona-ítem) es el punto entre la primera y la segunda opción de respuesta donde un encuestado tiene la misma probabilidad de elegir cualquiera de estas opciones de respuesta; el segundo umbral (etiquetado con un "2" en el mapa persona-ítem) es el punto entre la segunda y la tercera opción de respuesta donde un encuestado tiene la misma probabilidad de elegir cualquiera de estas opciones de respuesta; y así.
Queremos que nuestros umbrales en el mapa persona-ítem estén en el orden correcto: 1, 2, 3, 4 y así sucesivamente. Los umbrales desordenados indican un problema con nuestros ítems Por ejemplo, si los umbrales se enumeran en el orden 1, 2, 4, 3, entonces los datos nos dicen que es más probable que alguien supere el cuarto umbral antes del tercer umbral, lo cual no tiene sentido. Recodificamos las opciones de respuesta para crear menos umbrales, de modo que sea más fácil para ellos estar en orden.
Las funciones para realizar el Análisis Rasch cambian nuestras opciones de respuesta para que comiencen con 0. Esto se hace porque las funciones para realizar el análisis lo requieren. Por ejemplo, nuestra encuesta tiene preguntas que tienen opciones de respuesta que van del 1 al 5, pero internamente la función cambia estas opciones de respuesta para que varíen de 0 a 4. En consecuencia, es un poco más sencillo interpretar qué opciones de respuesta necesitan ser recodificadas directamente de las etiquetas de los umbrales. Por ejemplo, si un ítem está desordenado en el patrón 1, 2, 4, 3, esto significa que los umbrales 4 y 3 están fuera de orden. Esto también significa que podemos recodificar las opciones de respuesta transformadas 4 y 3 para combinar estos umbrales.
Cuando queremos recodificar un ítem, proporcionamos a la función instrucciones sobre a qué asignar las opciones de respuesta. Por ejemplo, digamos que un ítem `var` tiene umbrales desordenados en el patrón 1, 2, 4, 3. Ahora queremos combinar el cuarto y el tercer umbral para que el ítem se ordene. `var` tiene opciones de respuesta que van de 0 a 4 (después de haber cambiado del original por una sustracción de 1), por lo que queremos combinar las opciones de respuesta 3 y 4 para el ítem para combinar estos dos umbrales. Hacemos esto diciendo a la función que mapee las opciones de respuesta actuales de 0, 1, 2, 3, 4 a 0, 1, 2, 3, 3. Esto significa que todas las respuestas de "4" ahora se recodifican como "3" . Ahora solo tendremos 4 opciones de respuesta diferentes, lo que significa que tendremos 3 umbrales diferentes, que ahora esperamos que estén en el orden correcto.
Esto se aclarará a medida que trabajemos en el ejemplo.
## Testlet1_Recode1
En la siguiente iteración, intentaremos recodificar las opciones de respuesta de nuestro testlet para que el modelo pueda ejecutarse.
Ejecutaremos el comando como abajo:
```{r adult-t1r1-example}
testlet1_recode1 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode1",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5"
)
```
La diferencia entre el modelo Testlet1 y este modelo es que ahora hemos agregado una estrategia de recodificación. Recodificaremos las opciones de respuesta del testlet `workschool` a 0,1,2,3,4,5,6,7,7. Esto significa que todas las opciones de respuesta permanecerán igual, excepto las opciones 5 a 8 están combinadas.
Después de ejecutar el comando, vemos que el modelo se puede calcular normalmente.
Primero verificamos `LID_plot.pdf` para ver si hemos podido eliminar la correlación del elemento. En este archivo, vemos el mensaje _"No LID found"_, lo que significa que nuestra estrategia de prueba fue efectiva.
A continuación, verificamos el gráfico scree en el archivo `parallel_analysis_scree.pdf` para asegurarnos de que se mantiene nuestra unidimensionalidad. De hecho, parece muy similar al modelo inicial, que es lo que esperamos.
A continuación, verificamos el mapa persona-ítem en `PImap.pdf`. Podemos ver en este archivo que todos los elementos aún están desordenados, por lo que es probable que esto sea lo próximo que tengamos que cuidar en la próxima iteración del modelo.
```{r adult-t1r1-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode1/PImap.png")
```
Finalmente verificaremos el ajuste del ítem y el ajuste general del modelo en `item_fit.csv` y `Targeting.csv`, respectivamente. Podemos ver que todos estos valores siguen siendo buenos: cada ítem aún tiene estadísticas de infit y outfit entre 0.5 y 1.5, y el PSI aún es 0.82.
## Testlet1_Recode2
A continuación, intentaremos recodificar elementos para crear umbrales ordenados. Estamos más preocupados por tener los artículos individuales (todo lo que no es un testlet) ordenados.
Hay varias formas de elegir la estrategia de recodificación. En general, desea hacer la cantidad mínima de recodificación necesaria para alcanzar los umbrales ordenados. Primero intentaremos combinar los dos primeros umbrales para todos los elementos que no sean el testlet. Veremos para qué elementos funciona esto y probaremos una nueva estrategia en la siguiente iteración para los elementos en los que no funcionó.
```{r adult-t1r2-example}
testlet1_recode2 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode2",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,3)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,3"
)
```
Podemos ver en el nuevo mapa persona-ítem que esta estrategia no funcionó para ninguno de los ítems. Así que intentaremos una nueva estrategia en la próxima iteración.
```{r adult-t1r2-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode2/PImap.png")
```
También podemos verificar los otros archivos para ver si alguna otra suposición del Modelo Rasch ha sido violada con esta estrategia de recodificación. Pero debido a que estamos cambiando nuestra estrategia completamente en la próxima iteración, no es necesario prestar demasiada atención a los otros archivos para esta iteración.
## Testlet1_Recode3
Desde el mapa persona-ítem para el modelo de inicio, podemos ver que nuestros ítems están desordenados de una manera un poco complicada: muchos ítems tienen umbrales en los órdenes 2, 4, 1, 3 o 2, 3, 4, 1. Por lo general, si un ítem tiene umbrales desordenados en un patrón bastante sencillo (por ejemplo, 1, 2, 4, 3 o 2, 1, 3, 4), entonces la estrategia de recodificación es sencilla. Por ejemplo, con un desorden de 1, 2, 4, 3, está claro que las opciones de respuesta 3 y 4 deberían estar combinadas. Con un desorden de 2, 1, 3, 4, entonces las opciones de respuesta de 1 y 2 deberían combinarse.
En nuestro caso, el desorden es bastante complicado, por lo que la estrategia de recodificación es menos directa y probablemente tendrá que ser más extrema. En esta iteración, intentaremos colapsar dos conjuntos de opciones de respuesta: colapsaremos 1 con 2 y 3 con 4, como se muestra a continuación.
```{r adult-t1r3-example}
testlet1_recode3 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode3",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,2)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,2"
)
```
¡Podemos ver con esta estrategia de recodificación que los umbrales ahora están ordenados para la mayoría de los artículos! El único elemento para el que no funcionó es `EF6`, para lo cual tendremos que probar una estrategia diferente en la próxima iteración.
```{r adult-t1r3-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode3/PImap.png")
```
Avanzamos en nuestro desordenamiento de umbrales, pero debemos asegurarnos de que las otras suposiciones del Modelo Rasch no se hayan violado con esta nueva estrategia. Verificamos `LID_plot.pdf` y vemos que todavía hemos logrado la independencia del elemento. También verificamos el gráfico scree en `parallel_analysis_scree.pdf` para ver si todavía tenemos unidimensionalidad. Finalmente, también verificamos `item_fit.csv` y `Targeting.csv` y vemos que los valores también son aceptables en estos archivos. Así que procederemos con una estrategia de recodificación alterada en la siguiente iteración.
## Testlet1_Recode4
Todavía tenemos dos elementos desordenados: `EF6` y `workschool`. Por lo general, no nos preocupa que los testlets se desordenen porque no son elementos incluidos originalmente en el cuestionario. Podríamos recodificar `workschool` si el ajuste del ítem fuera muy pobre, pero en nuestro modelo mantiene el ajuste adecuado del ítem según las estadísticas de _infit_ y _outfit_, por lo que no lo recodificaremos.
Por lo tanto, en esta iteración solo intentaremos resolver el desorden de `EF6`. Intentaremos combinar las tres opciones de respuesta del medio, como se muestra a continuación.
```{r adult-t1r4-example}
testlet1_recode4 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode4",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF7,EF8,EF9,EF10" = c(0,1,1,2,2),
EF6 = c(0,1,1,1,2)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else except EF6 to 0,1,1,2,2, EF6 to 0,1,1,1,2"
)
```
Después de ejecutar este modelo, vemos que se ha resuelto el desorden para `EF6`. ¡Todos los artículos individuales ahora tienen umbrales ordenados!
```{r adult-t1r4-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode4/PImap.png")
```
También revisaremos los otros archivos para asegurarnos de que se hayan mantenido nuestros otras suposiciones del Modelo Rasch. Verificamos `LID_plot.pdf` y vemos que todavía hemos logrado la independencia del ítem. También verificamos el gráfico scree en `parallel_analysis_scree.pdf` para ver si todavía tenemos unidimensionalidad. Finalmente, también verificamos `item_fit.csv` y `Targeting.csv` y vemos que los valores también son aceptables en estos archivos.
Todas nuestras suposiciones del Modelo Rasch se han alcanzado razonablemente, ¡así que esto significa que podemos terminarnos! Hemos terminado nuestro Análisis Rasch para este conjunto de preguntas. Los datos con las puntuaciones se encuentran en el archivo `Data_final.csv`. Discutiremos qué hacer con estos puntajes en secciones posteriores.
# Mejores prácticas
Lea el vignette [Mejores prácticas con Análisis Rasch](c5_best_practices_ES.html) para aprender más sobre principios generales para usar.
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c3_rasch_adults_ES.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
## ----rasch-mds-children-help--------------------------------------------------
# ?rasch_mds_children
## ----rasch-mds-children-example-----------------------------------------------
# rasch_mds_children(df = df_children,
# vars_id = "HHID",
# vars_group = "age_cat",
# vars_metric_common = paste0("child", c(1:10)),
# vars_metric_grouped = list(
# "Age2to4" = paste0("child", c(12,15,16,19,20,24,25)),
# "Age5to9" = paste0("child", c(11,13,14,17,18,20,21,22,23,24,25,27)),
# "Age10to17" = paste0("child", c(11,13,14,17,18,20,21,22,23,25,26,27))),
# TAM_model = "PCM2",
# resp_opts = 1:5,
# has_at_least_one = 4:5,
# max_NA = 10,
# print_results = TRUE,
# path_parent = "~/Desktop/",
# model_name = "Start",
# testlet_strategy = NULL,
# recode_strategy = NULL,
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Initial run")
#
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c4_rasch_children_EN.R
|
---
title: "4 - Rasch Analysis for MDS data from children"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{4 - Rasch Analysis for MDS data from children}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
As already mentioned, a different process must be used to calculate disability scores for children. Children at different ages are incredibly different, and thus have different items pertaining to them in the questionnaire.
In the Capacity section of the children questionnaire, items are applied to all children aged 2 to 17, without age-specific filters. In this case, a multigroup analysis must be performed. This is essentially the same as performing a Rasch Model as for adults, however we alert the program to the fact that we have very different groups responding to the questionnaire--that is, different age groups. We use the age groups 2 to 4, 5 to 9, and 10 to 17.
In the Performance section of the children questionnaire, there is a set of common questions for all children and a set of questions with age-specific filters. In this case, a multigroup analysis is first performed on all the common items, as with the Capacity questions. Then this multigroup model is used to calibrate an additional score using all of the age-specific questions. This is called "anchoring"--we are anchoring the results of the age-specific questions on the results from the common set of questions. This must be done in order to make the disability scores obtained for children comparable across age groups.
# Structure
The `whomds` package also contains functions to perform Rasch Anaylsis for children.
To perform Rasch Analysis for children, only one function needs to be used: `rasch_mds_children()`. This is a wrapper function, like `rasch_mds()` for adults. `rasch_mds_children()` utilizes all the other `rasch_*()` functions to perform the analysis. These other `rasch_*()` functions used for children are:
* `rasch_df_nest()`
* `rasch_drop()`
* `rasch_factor()`
* `rasch_model_children()`
* `rasch_quality_children()`
* `rasch_quality_children_print()`
* `rasch_recode()`
* `rasch_rescale_children()`
* `rasch_split()`
* `rasch_split_age()`
* `rasch_testlet()`
You only need to use the function `rasch_mds_children()`. But if you wanted to perform your analysis in a more customized way, you could work with the internal functions directly.
# Output
After each iteration of the Rasch Model, the codes above produce a variety of files that will tell you how well the data fit the assumptions of the model at this iteration. The most important files are the ones below. We will explain each in detail below.
* Local item dependence spreadsheets and plots:
+ `LID_plot_Multigroup.pdf` and `LID_above_0.2_Multigroup.csv` - shows correlated items for multigroup model
+ `LID_plotAge2to4.pdf` and `LID_above_0.2_Age2to4.csv` - shows correlated items for ages 2 to 4 for anchored model
+ `LID_plotAge5to9.pdf` and `LID_above_0.2_Age5to9.csv` - shows correlated items for ages 5 to 9 for anchored model
+ `LID_plotAge10to17.pdf` and `LID_above_0.2_Age10to17.csv` - shows correlated items for ages 10 to 17 for anchored model
* Scree plots:
+ `ScreePlot_Multigroup_PCM2.pdf` - scree plot for multigroup model
+ `ScreePlot_Anchored_PCM2_Age2to4.pdf` - scree plot for ages 2 to 4 for anchored model
+ `ScreePlot_Anchored_PCM2_Age5to9.pdf` - scree plot for ages 5 to 9 for anchored model
+ `ScreePlot_Anchored_PCM2_Age10to17.pdf` - scree plot for ages 10 to 17 for anchored model
* Locations of persons and items:
+ `WrightMap_multigroup.pdf` - locations of persons and items for multigroup model
+ `WrightMap_anchored_Age2to4.pdf` - locations of persons and items for ages 2 to 4 for anchored model
+ `WrightMap_anchored_Age5to9.pdf` - locations of persons and items for ages 5 to 9 for anchored model
+ `WrightMap_anchored_Age10to17.pdf` - locations of persons and items for 10 to 17 for anchored model
* Item fit:
+ `PCM2_itemfit_multigroup.xlsx` - item fit for multigroup model
+ `PCM2_itemfit_anchored.xlsx` - item fit for anchored model
* Model fit:
+ `PCM2_WLE_multigroup.txt` - reliability of model for multigroup model
+ `PCM2_WLE_anchored.txt` - reliability of model for anchored model
# Arguments of `rasch_mds_children()`
In this section we will examine each argument of the function `rasch_mds_children()`. The help file for the function also describes the arguments. Help files for functions in `R` can be accessed by writing `?` before the function name, like so:
```{r rasch-mds-children-help}
?rasch_mds_children
```
Below is an example of a use of the function `rasch_mds_children()`:
```{r rasch-mds-children-example}
rasch_mds_children(df = df_children,
vars_id = "HHID",
vars_group = "age_cat",
vars_metric_common = paste0("child", c(1:10)),
vars_metric_grouped = list(
"Age2to4" = paste0("child", c(12,15,16,19,20,24,25)),
"Age5to9" = paste0("child", c(11,13,14,17,18,20,21,22,23,24,25,27)),
"Age10to17" = paste0("child", c(11,13,14,17,18,20,21,22,23,25,26,27))),
TAM_model = "PCM2",
resp_opts = 1:5,
has_at_least_one = 4:5,
max_NA = 10,
print_results = TRUE,
path_parent = "~/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run")
```
The first argument is `df`. This argument is for the data. The data object should be individual survey data, with one row per individual. Here the data is stored in an object `df_children`, which is a data set included in the `whomds` package. To find out more about `df_children` please look at its help file by running: `?df_children`
The next argument is `vars_id`, which is the name of the column used to uniquely identify individuals. Here the ID column is called `HHID`.
The next argument is `vars_group`, which is a string with the column name identifying groups, specifically age groups in this case. Here the age group column is `age_cat`.
The next two arguments specify the variables used to build the metric.
`vars_metric_common` is a character vector with the names of the items that every individual in the same answers.
`vars_metric_grouped` is a named list of character vectors with the items to use in the Rasch Analysis per group from the variable specified in `vars_group`. The list should have names corresponding to the different groups (for example, `Age2to4`, `Age5to9` and `Age10to17`), and contain character vectors of the corrsponding items for each group.
If only `vars_metric_common` is specified, then a multigroup analysis will be performed. If `vars_metric_common` and `vars_metric_grouped` are both specified, then an anchored analysis will be performed. `vars_metric_grouped` cannot be specified on its own.
The next argument is `TAM_model`. This is a string that identifies which Item Response Theory model to use. This value is passed to the function from the `TAM` package used to calculate the Rasch Model. The default is `"PCM2"`, which specifies the Rasch Model.
The next argument is `resp_opts`. This is a numeric vector with the possible response options for `vars_metric_common` and `vars_metric_grouped`. In this survey, the questions have response options 1 to 5. So here `resp_opts` is equal to a numeric vector of length 5 with the values `1`, `2`, `3`, `4` and `5`.
The next argument is `has_at_least_one`. This is a numeric vector with the response options that a respondent must have at least one of in order to be included in the metric calculation. This argument is required because often Rasch Analysis of children data is more difficult because of the extreme skewness of the responses. For this reason, it is often advisable to build a scale only with the respondents on the more severe end of the disability continuum, for example only with those respondents who answered 4 or 5 to at least one question. By specifying `has_at_least_one`, the function will only build a scale among those who answered `has_at_least_one` in at least one question from `vars_metric_common` and `vars_metric_grouped`. The default is `4:5`, which means the scale will be created only with children who answered 4 or 5 to at least one question in `vars_metric_common` and `vars_metric_grouped`. The scores created can be reunited with the excluded children post-hoc.
The next argument is `max_NA`. This is a numeric value for the maximum number of missing values allowed for an individual to be still be considered in the analysis. Rasch Analysis can handle individuals having a few missing values, but too many will cause problems in the analysis. In general all individuals in the sample should have fewer than 15% missing values. Here `max_NA` is set to `10`, meaning individuals are allowed to have a maximum of ten missing values out of the questions in `vars_metric_common` and `vars_metric_grouped` to still be included in the analysis.
The next argument is `print_results`, which is either `TRUE` or `FALSE`. When it is `TRUE`, files will be saved onto your computer with results from the Rasch iteration. When it is `FALSE`, files will not be saved.
The next argument is `path_parent`. This is a string with the path to the folder where the results of multiple models will be saved, assuming `print_results` is `TRUE`. The folder in `path_parent` will then contain separate folders with the names specified in `model_name` at each iteration. In the function call above, all results will be saved on the Desktop. Note that when writing paths for `R`, the slashes should all be: `/` (NOT `\`). Be sure to include a final `/` on the end of the path.
The next argument is `model_name`. This is equal to a string where you give a name of the model you are running. This name will be used as the name of the folder where all the output will be saved on your computer, if `print_results` is `TRUE`. The name you give should be short but informative. For example, you may call your first run "Start", as it is called here, if you create a testlet in your second run perhaps you can call it "Testlet1", etc. Choose whatever will be meaningful to you.
The next arguments are `testlet_strategy`, `recode_strategy`, `drop_vars` and `split_strategy`. These are arguments that control how the data is used in each iteration of the Rasch Model. These are specified in the same way as for adult models, as described in the above sections. Here they are all set to `NULL`, which means they are not used in the iteration of Rasch Analysis shown here.
The last argument is `comment`. This is equal to a string where you can write some free-text information about the current iteration so that when you are looking at the results later you can remember what you did and why you did it. It is better to be more detailed, because you will forget why you chose to run the model in this particular way. This comment will be saved in a file `Comment.txt`. Here the comment is just `"Initial run"`.
# Example
## Differences from adult models
We have already discussed differences in the command required to compute the Rasch Model for children. To run this model, a different `R` package is available: `TAM`. This package can be more complicated to use than `eRm` (the package used for adults), but it allows for greater flexibility, and thus allows us to compute the multigroup and anchored analyses that we require.
With the `TAM` package, we are also able to compute different types of models. By default the `whomds` package computes results using the Partial Credit Model (the normal polytomous Rasch Model). The PCM is specified in `TAM` with the argument `TAM_model` set to `"PCM2"`.
Another option for `TAM_model` is `"GPCM"`, which tells the program to calculate a Generalized Partial Credit Model (GPCM). The GPCM differs from the PCM in that relaxes the uniform discriminating power of items. In other words, the GPCM allows for some items to be better able to identify people's abilities than other items.
We focus on PCM because we can obtain the scale we seek with this model.
## Improving model quality
As mentioned previously, generally the distribution of children's answers is much more heavily skewed towards the "no disability" end of the scale, so it is harder to build a quality metric. **Your model will be greatly improved if you only build it among children who indicate having some sort of level of problems in at least one of the domains.** This is why the default for the argument `has_at_least_one` of `rasch_children()` is `4:5`. We recommend keeping this default.
Collapsing response options may also improve the quality of your scale. We also recommend trying to build a scale where all items are recoded to 0,1,1,2,2--in other words, collapse the 2nd and 3rd response options and the 3rd and the 4th response options.
## Important output to examine
The output from the iterations of the Rasch Model for children using the WHO codes is very similar to that of the adult models. However, for the anchored models (for Performance) in particular, for most types of files there is a separate file for each age group. The quality of the model may vary across age groups, and all the information must be assessed simultaneously in order to determine how to adjust the data.
There are a couple of key differences we will highlight. In order to assess the model fit (targeting) of the model, open the file `PCM2_WLE.txt` and analyze the number after `"WLE Reliability = "`. WLE stands for "weighted likelihood estimator", and it corresponds to the PSI we used to assess model fit for the adult models. Similarly, for good model fit, we would like to see this number be at least greater than 0.7, ideally greater than 0.8 or more.
The person-item map is also different for the children model. The `TAM` package works with another package called `WrightMap` to produce, aptly called, Wright Maps. These are very similar to the person item maps we used previously, except the type of thresholds displayed are different. The Wright Map displays the "Thurstonian Thresholds", and these thresholds by definition will never be disordered. Hence is reasonable to generally ignore recoding response options for the children, unless you would like to collapse empty response options or attempt to improve the spread of the threshold locations to better target the persons' abilities.
As with adults, the new rescaled scores for children are located in the file `Data_final.csv`.
# Best practices
Go to the [Best Practices in Rasch Analysis](c5_best_practices_EN.html) vignette to read more about general rules to follow.
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c4_rasch_children_EN.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
## ----rasch-mds-children-help--------------------------------------------------
# ?rasch_mds_children
## ----rasch-mds-children-example-----------------------------------------------
# rasch_mds_children(df = df_children,
# vars_id = "HHID",
# vars_group = "age_cat",
# vars_metric_common = paste0("child", c(1:10)),
# vars_metric_grouped = list(
# "Age2to4" = paste0("child", c(12,15,16,19,20,24,25)),
# "Age5to9" = paste0("child", c(11,13,14,17,18,20,21,22,23,24,25,27)),
# "Age10to17" = paste0("child", c(11,13,14,17,18,20,21,22,23,25,26,27))),
# TAM_model = "PCM2",
# resp_opts = 1:5,
# has_at_least_one = 4:5,
# max_NA = 10,
# print_results = TRUE,
# path_parent = "~/Desktop/",
# model_name = "Start",
# testlet_strategy = NULL,
# recode_strategy = NULL,
# drop_vars = NULL,
# split_strategy = NULL,
# comment = "Initial run")
#
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c4_rasch_children_ES.R
|
---
title: "4 - Análisis Rasch con los datos de niños de MDS"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{4 - Análisis Rasch con los datos de niños de MDS}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
Como ya se mencionó, se debe utilizar un proceso diferente para calcular los puntajes de discapacidad para los niños. Los niños de diferentes edades son increíblemente diferentes y, por lo tanto, tienen diferentes ítems pertenecientes a ellos en el cuestionario.
En la sección de Capacidad del cuestionario para niños, los ítems se aplican a todos los niños de 2 a 17 años, sin filtros específicos para cada edad. En este caso, se debe realizar un análisis multigrupo. Esto es esencialmente lo mismo que realizar un modelo de Rasch para adultos, sin embargo, alertamos al programa al hecho de que tenemos grupos muy diferentes que responden al cuestionario, es decir, diferentes grupos de edad. Usamos los grupos de edad 2 a 4, 5 a 9, y 10 a 17.
En la sección Desempeño del cuestionario para niños, hay un conjunto de preguntas comunes para todos los niños y un conjunto de preguntas con filtros específicos para cada grupo de edad. En este caso, primero se realiza un análisis multigrupo en todos los ítems comunes, como en las preguntas de Capacidad. Luego, este modelo multigrupo se usa para calibrar una puntuación adicional utilizando todas las preguntas específicas de la edad. Esto se llama "anclaje": estamos anclando los resultados de las preguntas específicas por edad en los resultados del conjunto común de preguntas. Esto debe hacerse para que los puntajes de discapacidad obtenidos para los niños sean comparables en todos los grupos de edad.
# Estructura
El paquete `whomds` también contiene funciones para realizar Rasch Anaylsis para niños.
Para realizar el Análisis Rasch para niños, solo se necesita usar una función: `rasch_mds_children()`. Esta es una función de envoltorio, como `rasch_mds()` para adultos. `rasch_mds_children()` utiliza todas las demás funciones `rasch_*()` para realizar el análisis. Estas otras funciones `rasch_*()` usadas para niños son:
* `rasch_df_nest()`
* `rasch_drop()`
* `rasch_factor()`
* `rasch_model_children()`
* `rasch_quality_children()`
* `rasch_quality_children_print()`
* `rasch_recode()`
* `rasch_rescale_children()`
* `rasch_split()`
* `rasch_split_age()`
* `rasch_testlet()`
Solo necesitas usar la función `rasch_mds_children()`. Pero si desea realizar su análisis de una manera más personalizada, puede trabajar directamente con las funciones internas.
# Salida
Después de cada iteración del Modelo Rasch, los códigos anteriores producen una variedad de archivos que le dirán qué tan bien los datos se ajustan a las suposiciones del modelo en esta iteración. Los archivos más importantes son los de abajo. Vamos a explicar cada uno en detalle a continuación.
* Hojas de cálculo y gráficos de dependencia local de ítems:
+ `LID_plot_Multigroup.pdf` y `LID_above_0.2_Multigroup.csv` - muestra ítems correlacionados para el modelo multigrupo
+ `LID_plotAge2to4.pdf` y `LID_above_0.2_Age2to4.csv` - muestra ítems correlacionados para edades de 2 a 4 para el modelo anclado
+ `LID_plotAge5to9.pdf` y `LID_above_0.2_Age5to9.csv` - muestra ítems correlacionados para edades de 5 a 9 para el modelo anclado
+ `LID_plotAge10to17.pdf` y `LID_above_0.2_Age10to17.csv` - muestra ítems correlacionados para edades de 10 a 17 para el modelo anclado
* Gráficos scree:
+ `ScreePlot_Multigroup_PCM2.pdf` - gráfico scree para el modelo multigrupo
+ `ScreePlot_Anchored_PCM2_Age2to4.pdf` - gráfico scree para para edades de 2 a 4 para el modelo anclado
+ `ScreePlot_Anchored_PCM2_Age5to9.pdf` - gráfico scree para para edades de 5 a 9 para el modelo anclado
+ `ScreePlot_Anchored_PCM2_Age10to17.pdf` - gráfico scree para para edades de 10 a 17 para el modelo anclado
* Ubicaciones de personas e ítems:
+ `WrightMap_multigroup.pdf` - ubicaciones de personas e ítems para for multigroup model
+ `WrightMap_anchored_Age2to4.pdf` - ubicaciones de personas e ítems para edades de 2 a 4 para el modelo anclado
+ `WrightMap_anchored_Age5to9.pdf` - ubicaciones de personas e ítems para edades de 5 a 9 para el modelo anclado
+ `WrightMap_anchored_Age10to17.pdf` - ubicaciones de personas e ítems para edades de 10 a 17 para el modelo anclado
* Ajuste de ítems:
+ `PCM2_itemfit_multigroup.xlsx` - ajuste de ítems para el modelo multigrupo
+ `PCM2_itemfit_anchored.xlsx` - ajuste de ítems para el modelo anclado
* Ajuste al modelo:
+ `PCM2_WLE_multigroup.txt` - fiabilidad del modelo multigrupo
+ `PCM2_WLE_anchored.txt` - fiabilidad del modelo anclado
# Argumentos de `rasch_mds_children()`
En esta sección examinaremos cada argumento de la función `rasch_mds_children()`. El archivo de ayuda para la función también describe los argumentos. Se puede acceder a los archivos de ayuda para las funciones en `R` escribiendo `?` antes del nombre de la función, de esta manera:
```{r rasch-mds-children-help}
?rasch_mds_children
```
A continuación se muestra un ejemplo de uso de la función `rasch_mds_children()`:
```{r rasch-mds-children-example}
rasch_mds_children(df = df_children,
vars_id = "HHID",
vars_group = "age_cat",
vars_metric_common = paste0("child", c(1:10)),
vars_metric_grouped = list(
"Age2to4" = paste0("child", c(12,15,16,19,20,24,25)),
"Age5to9" = paste0("child", c(11,13,14,17,18,20,21,22,23,24,25,27)),
"Age10to17" = paste0("child", c(11,13,14,17,18,20,21,22,23,25,26,27))),
TAM_model = "PCM2",
resp_opts = 1:5,
has_at_least_one = 4:5,
max_NA = 10,
print_results = TRUE,
path_parent = "~/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run")
```
El primer argumento es `df`. Este argumento es para los datos. El objeto de datos debe ser datos de encuestas individuales, con una fila por persona. Aquí los datos se almacenan en un objeto `df_children`, que es un base de datos incluido en el paquete` whomds`. Para obtener más información sobre `df_children`, consulta su archivo de ayuda ejecutando:`?df_children`
El siguiente argumento es `vars_id`, que es el nombre de la columna utilizada para identificar de forma única a los individuos. Aquí la columna de ID se llama `HHID`.
El siguiente argumento es `vars_group`, que es una cadena con el nombre de la columna que identifica grupos, específicamente grupos de edad en este caso. Aquí la columna del grupo de edad es `age_cat`.
Los siguientes dos argumentos especifican las variables utilizadas para construir la métrica.
`vars_metric_common` es un vector de caracteres con los nombres de los ítems a los que cada individuo responde.
`vars_metric_grouped` es una lista nombrada de vectores de caracteres con los ítems a usar en el Análisis de Rasch por grupo de la variable especificada en `vars_group`. La lista debe tener nombres correspondientes a los diferentes grupos (por ejemplo, `Age2to4`,` Age5to9` y `Age10to17`), y contener vectores de caracteres de los elementos correspondientes para cada grupo.
Si solo se especifica `vars_metric_common`, entonces se realizará un análisis multigrupo. Si se especifican `vars_metric_common` y `vars_metric_grouped`, entonces se realizará un análisis anclado. `vars_metric_grouped` no se puede especificar por sí solo.
El siguiente argumento es `TAM_model`. Esta es una cadena que identifica qué modelo de IRT utilizar. Este valor se pasa a la función del paquete `TAM` utilizado para calcular el modelo de Rasch. El valor predeterminado es `"PCM2"`, que especifica el modelo de Rasch.
El siguiente argumento es `resp_opts`. Este es un vector numérico con las posibles opciones de respuesta para `vars_metric_common` y `vars_metric_grouped`. En esta encuesta, las preguntas `EF1` a `EF12` tienen las opciones de respuesta 1 a 5. Entonces, `resp_opts` es igual a un vector numérico de longitud 5 con los valores `1`, `2`,` 3`, `4` y `5`.
El siguiente argumento es `has_at_least_one`. Este es un vector numérico con las opciones de respuesta que un encuestado debe tener al menos una para ser incluido en el cálculo de la métrica. Este argumento es necesario porque a menudo el análisis de Rasch de los datos de los niños es más difícil debido a la extrema asimetría de las respuestas. Por esta razón, a menudo es aconsejable construir una escala solo con los encuestados en el extremo más grave del continuo de discapacidad, por ejemplo, solo con los encuestados que respondieron 4 o 5 a al menos una pregunta. Al especificar `has_at_least_one`, la función solo construirá una escala entre aquellos que respondieron `has_at_least_one` en al menos una pregunta de `vars_metric_common` y `vars_metric_grouped` El valor predeterminado es `4:5`, lo que significa que la escala se creará solo con hijos que respondieron 4 o 5 a al menos una pregunta en `vars_metric_common` y `vars_metric_grouped`. Los puntajes creados pueden reunirse con los niños excluidos post-hoc.
El siguiente argumento es `max_NA`. Este es un valor numérico para el número máximo de valores faltantes permitidos para que una persona aún se tenga en cuenta en el análisis. El Análisis de Rasch puede manejar a personas que tienen algunos valores faltantes, pero demasiados causarán problemas en el análisis. En general, todos los individuos en la muestra deben tener menos del 15% de valores faltantes. Aquí `max_NA` es `10`, lo que significa que se permite que los individuos tengan un máximo de dos valores faltantes de las preguntas en `vars_metric_common` y `vars_metric_grouped` para que aún se incluyan en el análisis.
El siguiente argumento es `print_results`, que es `TRUE` o `FALSE`. Cuando es `TRUE`, los archivos se guardarán en su computadora con los resultados de la iteración Rasch. Cuando es `FALSE`, los archivos no se guardarán.
El siguiente argumento es `path_parent`. Esta es una cadena con la ruta a la carpeta donde se guardarán los resultados de múltiples modelos, asumiendo que `print_results` es `TRUE`. La carpeta en `path_parent` contendrá carpetas separadas con los nombres especificados en `model_name` en cada iteración. En la ejecución de la función anterior, todos los resultados se guardarán en el Desktop. Ten en cuenta que al escribir rutas para `R`, todas las barras deberían ser: `/ `(NO `\`). Asegúrate de incluir un `/` final en el final de la ruta.
El siguiente argumento es `model_name`. Esto es igual a una cadena donde le das un nombre del modelo que estás ejecutando. Este nombre se usará como el nombre de la carpeta donde se guardará toda la salida en su computadora, si `print_results` es `TRUE`. El nombre que le des debe ser corto pero informativo. Por ejemplo, puede llamar a su primera ejecución "Start", como se llama aquí. Si creas un testlet en su segunda ejecución, quizás puedas llamarlo "Testlet1", etc. Elije lo que sea significativo para tí.
Los siguientes argumentos son `testlet_strategy`, `recode_strategy`, `drop_vars` y `split_strategy`. Estos son argumentos que controlan cómo se usan los datos en cada iteración del Modelo Rasch. Estos se especifican de la misma manera que en los modelos para adultos, como se describe en las secciones anteriores. Aquí están todos configurados en `NULL`, lo que significa que no se usan en la iteración del Análisis Rasch que se muestra aquí.
El último argumento es `comment`. Esto es igual a una cadena en la que puedes escribir cierta información de texto libre sobre la iteración actual para que cuando veas los resultados más adelante puedas recordar lo que hiciste y por qué lo hiciste. Es mejor ser más detallado, porque olvidarás por qué eligiste ejecutar el modelo de esta manera en particular. Este comentario se guardará en un archivo `Comment.txt`. Aquí el comentario es solo `"Initial run"`.
# Ejemplo
## Diferencias de modelos adultos
Ya hemos discutido las diferencias en el comando requerido para calcular el modelo de Rasch para niños. Para ejecutar este modelo, hay un paquete `R` diferente disponible: `TAM`. Este paquete puede ser más complicado de usar que `eRm` (el paquete utilizado para adultos), pero permite una mayor flexibilidad y, por lo tanto, nos permite calcular los análisis multigrupo y anclados que requerimos.
Con el paquete `TAM`, también podemos calcular diferentes tipos de modelos. Por defecto, el paquete `whomds` calcula los resultados utilizando el modelo de crédito parcial (el modelo de Rasch politomérico). El PCM se especifica en `TAM` con el argumento `TAM_model` igual a `"PCM2"`.
Otra opción para `TAM_model` es `"GPCM"`, que le dice al programa que calcule un Modelo de crédito parcial generalizado (GPCM). El GPCM se diferencia del PCM en que relaja el poder de discriminación uniforme de los artículos. Es decir, el GPCM permite que algunos ítems puedan identificar mejor las capacidades de las personas que otros ítems.
Nos enfocamos en PCM porque podemos obtener la escala que buscamos con este modelo.
## Mejorando la calidad del modelo
Como se mencionó anteriormente, en general, la distribución de las respuestas de los niños está mucho más inclinada hacia el final de la escala "sin discapacidad", por lo que es más difícil construir una métrica de calidad. **Su modelo mejorará enormemente si solo lo construye entre niños que indican tener algún tipo de nivel de problemas en al menos uno de los dominios.** Esta es la razón por la cual el valor predeterminado para el argumento `has_at_least_one` de `rasch_children()` es `4:5`. Recomendamos mantener este valor predeterminado.
Colapsando opciones de respuesta también puede mejorar la calidad de su escala. También recomendamos intentar construir una escala donde todos los ítems se recodifiquen a 0,1,1,2,2; en otras palabras, contraiga las opciones de respuesta 2a y 3a y las opciones de respuesta 3a y 4a.
## Salida importante para examinar
El resultado de las iteraciones del Modelo de Rasch para niños que utilizan los códigos de la OMS es muy similar al de los modelos para adultos. Sin embargo, para los modelos anclados (para Desempeño) en particular, para la mayoría de los tipos de archivos hay un archivo separado para cada grupo de edad. La calidad del modelo puede variar según los grupos de edad, y toda la información debe evaluarse simultáneamente para determinar cómo ajustar los datos.
Hay un par de diferencias clave que vamos a destacar. Para evaluar el ajuste del modelo (_targeting_) del modelo, abra el archivo `PCM2_WLE.txt` y analice el número después de `"WLE Reliability = "`. WLE significa "estimador de probabilidad ponderada" (en inglés _weighted likelihood estimator_), y corresponde al PSI que usamos para evaluar el ajuste del modelo para los modelos adultos. De manera similar, para un buen ajuste del modelo, nos gustaría ver que este número sea al menos mayor que 0.7, idealmente mayor que 0.8 o más.
El mapa persona-ítem también es diferente para el modelo de los niños. El paquete `TAM` utiliza otro paquete llamado` WrightMap` para producir _Wright Maps_. Estos son muy similares a los mapas de persona-ítem que utilizamos anteriormente, excepto que el tipo de umbrales que se muestran son diferentes. El _Wright Map_ muestra los "Umbrales Thurstonianos", y estos umbrales por definición nunca serán desordenados. Por lo tanto, es razonable no recodificar las opciones de respuesta para los niños, a menos que desee contraer las opciones de respuesta vacías o intentar mejorar la distribución de las ubicaciones de umbral para orientar mejor las capacidades de las personas.
Al igual que con los adultos, los nuevos puntajes reescalados para niños se encuentran en el archivo `Data_final.csv`.
# Mejores prácticas
Lea el vignette [Mejores prácticas con Análisis Rasch](c5_best_practices_ES.html) para aprender más sobre principios generales para usar.
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c4_rasch_children_ES.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c5_best_practices_EN.R
|
---
title: "5 - Best practices with Rasch Analysis"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{5 - Best practices with Rasch Analysis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
Here we will discuss some general principles about how to implement the Rasch Model for your data.
* **It is easiest to run the model with a large sample and few items.** Samples of less than 200 people can be problematic, especially if there are a large number of items (20+) and responses to the items are not distributed evenly.
* In general, **minimal data adjustment is best**. Always try to see if you can make as few adjustments to your data as possible. This means the outcome of your analysis will better support your original survey instrument.
* **Try to make testlets only among items that are conceptually similar.** It is easier to justify combining items that are very similar (for instance, "feeling depressed" and "feeling anxious") than items that are extremely different (for instance, "walking 100m" and "remembering important things"). If you have high correlation among items that are very conceptually different, this may point to other problems with the survey instrument that should likely be addressed.
* When recoding, **try to collapse only adjacent thresholds** For instance, if you see that thresholds are disordered in the pattern 2, 1, 3, 4, it is natural to try to collapse thresholds 2 and 1 because they are adjacent. It would not make sense to collapse thresholds 2 and 4 because they are not adjacent.
* When recoding, **leave the first response option alone and do not recode it**. This first response option represents an answer in the MDS of "no problems" or "no difficulty", and it is best to leave this response option alone as a baseline. There is a larger conceptual difference between having "no problems" and "few problems" than there is between having "few problems" and "some problems", so it makes less sense to collapse the first two response options than it does to collapse the 2nd and 3rd response options.
* **It is normal to have to run many iterations of the model** in order to find a solution that works best, especially if you have many items in your instrument.
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c5_best_practices_EN.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c5_best_practices_ES.R
|
---
title: "5 - Mejores prácticas con Análisis Rasch"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{5 - Mejores prácticas con Análisis Rasch}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
Aquí discutiremos algunos principios generales sobre cómo implementar el Modelo Rasch para tus datos.
* **Es más fácil ejecutar el modelo con una muestra grande y pocos ítems.** Las muestras de menos de 200 personas pueden ser problemáticas, especialmente si hay una gran cantidad de ítems (20+) y las respuestas a los ítems no son distribuido uniformemente
* En general, **el mínimo ajuste de datos es el mejor**. Siempre trata de ver si puedes hacer el mínimo ajuste posible a sus datos. Esto significa que el resultado de su análisis respaldará mejor su instrumento de encuesta original.
* **Trata de hacer testlets solo entre ítems que son conceptualmente similares.** Es más fácil justificar la combinación de ítems que son muy similares (por ejemplo, "sentirse deprimido" y "sentirse ansioso") que los ítems que son extremadamente diferentes (para ejemplo, "caminar 100m" y "recordar cosas importantes"). Si tienes una alta correlación entre los ítems que son muy diferentes conceptualmente, esto puede indicar otros problemas con el instrumento de la encuesta que probablemente deberían abordarse.
* Al recodificar, **intenta combinar solo umbrales adyacentes** Por ejemplo, si ves que los umbrales están desordenados en el patrón 2, 1, 3, 4, es natural tratar de contraer los umbrales 2 y 1 porque son adyacentes. No tendría sentido colapsar los umbrales 2 y 4 porque no son adyacentes.
* Al recodificar, **dejaa la primera opción de respuesta sola y no recodifícala**. Esta primera opción de respuesta representa una respuesta en el MDS de "no hay problemas" o "no hay dificultad", y es mejor dejar esta opción de respuesta sola como referencia. Hay una diferencia conceptual más grande entre "no tener problemas" y "pocos problemas" que entre tener "pocos problemas" y "algunos problemas", por lo que tiene menos sentido combinar las dos primeras opciones de respuesta que combinar las opciones de segunda y tercera respuesta.
* **Es normal tener que ejecutar muchas iteraciones del modelo** para encontrar una solución que funcione mejor, especialmente si tienes muchos ítems en su cuestionario.
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c5_best_practices_ES.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
library(tidyr)
library(dplyr)
library(whomds)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>",
survey.lonely.psu = "adjust")
## ----join-example-------------------------------------------------------------
# library(tidyverse)
# new_score <- read_csv("Data_final.csv") %>%
# select(c("ID", "rescaled"))
# merged_data <- original_data %>%
# left_join(new_score) %>%
# rename("DisabilityScore" = "rescaled")
## ----table-weightedpct-example1, eval=TRUE------------------------------------
#Remove NAs from column used for argument by_vars
df_adults_noNA <- df_adults %>%
filter(!is.na(disability_cat))
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = NULL,
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
## ----table-weightedpct-example2, eval=TRUE------------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
## ----table-weightedpct-example3, eval=TRUE------------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
## ----table-weightedpct-example4, eval=TRUE------------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
## ----table-weightedpct-example5, eval=TRUE------------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
)
## ----table-weightedpct-example5b, eval=TRUE-----------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
) %>%
pivot_wider(names_from = disability_cat, values_from = problems)
## ----table-unweightedpctn-example, eval=TRUE----------------------------------
table_unweightedpctn(df_adults_noNA,
vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"),
group_by_var = "disability_cat",
spread_by_group_by_var = TRUE)
## ----table-basicstats-example, eval=TRUE--------------------------------------
table_basicstats(df_adults_noNA, "HHID", "age_cat")
## ----plot-pop-pyramid, eval=TRUE, echo=FALSE----------------------------------
include_graphics("Images/pop_pyramid.png")
## ----plot-distribution, eval=TRUE, echo=FALSE---------------------------------
include_graphics("Images/distribution.png")
## ----plot-density, eval=TRUE, echo=FALSE--------------------------------------
include_graphics("Images/density.png")
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c6_after_rasch_EN.R
|
---
title: "6 - After Rasch Analysis: Descriptive Analysis"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{6 - After Rasch Analysis: Descriptive Analysis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
library(tidyr)
library(dplyr)
library(whomds)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>",
survey.lonely.psu = "adjust")
```
# Joining scores with original data
After you have finished with Rasch Analysis, the score is outputted in the file `Data_final.csv` in the column called `rescaled`. This file will only contain the individuals included in the analysis. Any individual who had too many missing values (`NA`) will not be in this file. It is often advisable to merge the original data with all individuals with the new scores. Any individual who did not have a score calculated will have an `NA` in this column.
This merge can be accomplished with the following code. First, open the library called `tidyverse` to access the necessary functions. Next, read in the `Data_final.csv` file and select only the columns you need: `ID` (or whatever the name of the individual ID column is in your data) and `rescaled`. The code below assumes that the file is in your working directory. You will have to include the full path to the file if it is not currently in your working directory. Finally, you can create an object `merged_data` that merges your original data, here represented with the object `original_data`, with the new score in a column renamed to `"DisabilityScore"` with the following code:
```{r join-example}
library(tidyverse)
new_score <- read_csv("Data_final.csv") %>%
select(c("ID", "rescaled"))
merged_data <- original_data %>%
left_join(new_score) %>%
rename("DisabilityScore" = "rescaled")
```
The sample data included in the `whomds` package called `df_adults` already has a Rasch score merged with it, in the column `disability_score`.
# Descriptive analysis
After calculating the disability scores using Rasch Analysis, you are now ready to analyze the results of the survey by calculating descriptive statistics. The `whomds` package contains functions to create tables and figures of descriptive statistics. This section will go over these functions.
## Tables
Descriptive statistics functions included in the `whomds` package are:
* `table_weightedpct()` - produces weighted tables of N or %
* `table_unweightedpctn()` - produces unweighted tables of N and %
* `table_basicstats()` - computes basic statistics of the number of members per group per household.
The arguments of each of these codes will be described below.
### `table_weightedpct()`
`whomds` contains a function called `table_weightedpct()` which calculates weighted results tables from the survey, disaggregated by specified variables. The arguments of this function are passed to functions in the package `dplyr`.
Below are the arguments of the function:
* `df` - the data frame with all the variables of interest
* `vars_ids` - variable names of the survey cluster ids
* `vars_strata` - variable names of the survey strata
* `vars_weights` - variable names of the weights
* `formula_vars` - vector of the column names of variables you would like to print results for
* `...` - captures expressions for filtering or transmuting the data. See the description of the argument `willfilter` below for more details
* `formula_vars_levels` - numeric vector of the factor levels of the variables in `formula_vars`. By default, the function assumes the variables have two levels: 0 and 1
* `by_vars` - the variables to disaggregate by
* `pct` - a logical variable indicating whether or not to calculate weighted percentages. Default is `TRUE` for weighted percentages. Set to `FALSE` for weighted N.
* `willfilter` - a variable that tells the function whether or not to filter the data by a particular value.
+ For example, if your `formula_vars` have response options of 0 and 1 but you only want to show the values for 1, then you would say `willfilter = TRUE`. Then at the end of your argument list you write an expression for the filter. In this case, you would say `resp==1`.
+ If you set `willfilter = FALSE`, then the function will assume you want to "transmute" the data, in other words manipulate the columns in some way, which for us often means to collapse response options. For example, if your `formula_vars` have 5 response options, but you only want to show results for the sum of options `"Agree"` and `"StronglyAgree"`, (after setting `spread_key="resp"` to spread the table by the response options) you could set `willfilter=FALSE`, and then directly after write the expression for the transmutation, giving it a new column name--in this case the expression would be `NewColName=Agree+AgreeStrongly`. Also write the names of the other columns you would like to keep in the final table.
+ If you leave `willfilter` as its default of `NULL`, then the function will not filter or transmute data.
* `add_totals` - a logical variable determining whether to create total rows or columns (as appropriate) that demonstrate the margin that sums to 100. Keep as the default `FALSE` to not include totals.
* `spread_key` - the variable to spread the table horizontally by. Keep as the default `NULL` to not spread the table horizontally.
* `spread_value` - the variable to fill the table with after a horizontal spread. By default this argument is `"prop"`, which is a value created internally by the function, and generally does not need to be changed.
* `arrange_vars` - the list of variables to arrange the table by. Keep as default `NULL` to leave the arrangement as is.
* `include_SE` - a logical variable indicating whether to include the standard errors in the table. Keep as the default `FALSE` to not include standard errors. As of this version of `whomds`, does not work when adding totals (`add_totals` is `TRUE`), spreading (`spread_key` is not `NULL`) or transmutting (`willfilter` is `FALSE`).
Here are some examples of how `table_weightedpct()` would be used in practice. Not all arguments are explicitly set in each example, which means they are kept as their default values.
#### Example 1: long table, one level of disaggregation
Let's say we want to print a table of the percentage of people in each disability level who gave each response option for a set of questions about the general environment. We would set the arguments of `table_weightedpct()` like this, and the first few rows of the table would look like this:
```{r table-weightedpct-example1, eval=TRUE}
#Remove NAs from column used for argument by_vars
df_adults_noNA <- df_adults %>%
filter(!is.na(disability_cat))
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = NULL,
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
```
The outputted table has 4 columns: the variable we disaggregated the data by (`disability_cat`, in other words the disability level), the item (`item`), the response option (`resp`), and the proportion (`prop`).
#### Example 2: wide table, one level of disaggregation
This long table from the above example is great for data analysis, but not great for reading with the bare eye. If we want to make it nicer, we convert it to "wide format" by "spreading" by a particular variable. Perhaps we want to spread by `disability_cat`. Our call to `table_weightedpct()` would now look like this, and the outputted table would be:
```{r table-weightedpct-example2, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
```
Now we can see our `prop` column has been spread horizontally for each level of `disability_cat`.
#### Example 3: wide table, one level of disaggregation, filtered
Perhaps, though, we are only interested in the proportions of the most extreme response option of 5. We could now add a filter to our call to `table_weightedpct()` like so:
```{r table-weightedpct-example3, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
```
Now you can see only the proportions for the response option of 5 are given.
#### Example 4: wide table, multiple levels of disaggregation, filtered
With `table_weightedpct()`, we can also add more levels of disaggregation by editing the argument `by_vars`. Here we will produce the same table as in Example 3 above but now disaggregated by disability level and sex:
```{r table-weightedpct-example4, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
```
#### Example 5: wide table, multiple levels of disaggregation, transmuted
Perhaps we are still interested not only in response option 5, but the sum of 4 and 5 together. We can do this by "transmuting" our table. To do this, we first choose to "spread" by `resp` by setting `spread_key="resp"`. This will convert the table to a wide format as in Example 2, but now each column will represent a response option. Then we set the transmutation by setting `willfilter=FALSE`, and adding expressions for the transmutation on the next line. We name all the columns we would like to keep and give an expression for how to create the new column of the sum of proportions for response options 4 and 5, here called `problems`:
```{r table-weightedpct-example5, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
)
```
If we would like to modify the table again so that `disability_cat` represents the columns again, we can feed this table into another function that will perform the pivot The function to pivot tables is called `pivot_wider()`, and it is in the `tidyr` package. To perform a second pivot, write the code like this:
```{r table-weightedpct-example5b, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
) %>%
pivot_wider(names_from = disability_cat, values_from = problems)
```
The `names_from` argument of the function `pivot_wider()` tells `R` which variable to use as the columns, and `values_from` tells `R` what to fill the columns with. The operator `%>%` is commonly referred to as a "pipe". It feeds the object before it into the first argument of the function after it. For example, if you have an object `x` and a function `f`, writing `x %>% f()` would be the equivalent as writing `f(x)`. People use "pipes" because they make long sequences of code easier to read.
### `table_unweightedpctn()`
`whomds` contains a function called `table_unweightedpctn()` that produces unweighted tables of N and %. This is generally used for demographic tables. Its arguments are as follows:
* `df` - the data frame with all the variables of interest
* `vars_demo` - vector with the names of the demographic variables for which the N and % will be calculated
* `group_by_var` - name of the variable in which the statistics should be stratified (e.g. `"disability_cat"`)
* `spread_by_group_by_var` - logical determining whether to spread the table by the variable given in `group_by_var`. Default is `FALSE`.
* `group_by_var_sums_to_100` - logical determining whether percentages sum to 100 along the margin of `group_by_var`, if applicable. Default is `FALSE`.
* `add_totals` - a logical variable determining whether to create total rows or columns (as appropriate) that demonstrate the margin that sums to 100. Keep as the default `FALSE` to not include totals.
Here is an example of how it is used:
```{r table-unweightedpctn-example, eval=TRUE}
table_unweightedpctn(df_adults_noNA,
vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"),
group_by_var = "disability_cat",
spread_by_group_by_var = TRUE)
```
### `table_basicstats()`
The function `table_basicstats()` computes basic statistics of the number of member per group per household. Its arguments are:
* `df` - a data frame of household data where the rows represent members of the households in the sample
* `hh_id` - string (length 1) indicating the name of the variable in `df` uniquely identifying households
* `group_by_var` - string (length 1) with name of variable in `df` to group results by
Here is an example of how it is used:
```{r table-basicstats-example, eval=TRUE}
table_basicstats(df_adults_noNA, "HHID", "age_cat")
```
## Figures
Descriptive statistics figure functions included in the `whomds` package are:
* `fig_poppyramid()` - produces a population pyramid figure for the sample
* `fig_dist()` - produces a plot of the distribution of a score
* `fig_density()` - produces a plot of the density of a score
The arguments of each of these codes will be described below.
### `fig_poppyramid()`
`whomds` contains a function called `fig_poppyramid()` that produces a population pyramid figure for the sample. This function takes as arguments:
* `df` - the data where each row is a member of the household from the household roster
* `var_age` - the name of the column in `df` with the persons' ages
* `var_sex` - the name of the column in `df` with he persons' sexes
* `x_axis` - a string indicating whether to use absolute numbers or sample percentage on the x-axis. Choices are `"n"` (default) or `"pct"`.
* `age_plus` - a numeric value indicating the age that is the first value of the oldest age group. Default is 100, for the last age group to be 100+
* `age_by` - a numeric value indicating the width of each age group, in years. Default is 5.
Running this function produces a figure like the one below:
```{r plot-pop-pyramid, eval=TRUE, echo=FALSE}
include_graphics("Images/pop_pyramid.png")
```
### `fig_dist()`
`whomds` contains a function called `fig_dist()` that produces a plot of the distribution of a score. WHO uses this function to show the distribution of the disability scores calculated with Rasch Analysis. Its arguments are:
* `df` - data frame with the score of interest
* `score` - character variable of score variable name ranging from 0 to 100; ex. `"disability_score"`
* `score_cat` - character variable of score categorization variable name, ex. `"disability_cat"`
* `cutoffs` - a numeric vector of the cut-offs for the score categorization
* `x_lab` - a string giving the x-axis label. Default is `"Score"`
* `y_max` - maximum value to use on the y-axis. If left as the default `NULL`, the function will calculate a suitable maximum automatically.
* `pcent` - logical variable indicating whether to use percent on the y-axis or frequency. Leave as default `FALSE` for frequency and give `TRUE` for percent.
* `pal` - a string specifying the type of color palette to use, passed to the function `RColorBrewer::brewer.pal()`. Default is `"Blues"`.
* `binwidth` - a numeric value giving the width of the bins in the histograph. Default is 5.
Running this function produces a figure like the one below.
```{r plot-distribution, eval=TRUE, echo=FALSE}
include_graphics("Images/distribution.png")
```
### `fig_density()`
`whomds` contains a function similar to `fig_dist()` called `fig_density()` that produces a plot of the density of a score. WHO uses this function to show the density distribution of the disability scores calculated with Rasch Analysis. Its arguments are:
* `df` - data frame with the score of interest
* `score` - character variable of score variable name ranging from 0 to 100; ex. `"disability_score"`
* `var_color` - a character variable of the column name to set color of density lines by. Use this variable if you could like to print the densities of different groups onto the same plot. Default is `NULL`.
* `var_facet` - a character variable of the column name for the variable to create a `ggplot2::facet_grid()` with, which will plot densities of different groups in side-by-side plots. Default is `NULL`.
* `cutoffs` - a numeric vector of the cut-offs for the score categorization
* `x_lab` - a string giving the x-axis label. Default is `"Score"`
* `pal` - a string specifying either a manual color to use for the color aesthetic, a character vector explictly specifying the colors to use for the color scale, or as the name of a palette to pass to `RColorBrewer::brewer.pal() ` with the name of the color palette to use for the color scale. Default is `"Paired"`
* `adjust` - a numeric value to pass to `adjust` argument of `ggplot2::geom_density()`, which controls smoothing of the density function. Default is 2.
* `size` - a numeric value to pass to `size` argument of `ggplot2::geom_density()`, which controls the thickness of the lines. Default is 1.5.
Running this function produces a figure like the one below.
```{r plot-density, eval=TRUE, echo=FALSE}
include_graphics("Images/density.png")
```
## Descriptive statistics templates
WHO also provides a template for calculating many descriptive statistics tables for use in survey reports, also written in `R`. If you would like a template for your country, please contact us (see DESCRIPTION for contact info).
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c6_after_rasch_EN.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
library(tidyr)
library(dplyr)
library(whomds)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>",
survey.lonely.psu = "adjust")
## ----join-example-------------------------------------------------------------
# library(tidyverse)
# new_score <- read_csv("Data_final.csv") %>%
# select(c("ID", "rescaled"))
# merged_data <- original_data %>%
# left_join(new_score) %>%
# rename("DisabilityScore" = "rescaled")
## ----table-weightedpct-example1, eval=TRUE------------------------------------
#Quitar NAs de la columna utilizada para el argumento by_vars
df_adults_noNA <- df_adults %>%
filter(!is.na(disability_cat))
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = NULL,
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
## ----table-weightedpct-example2, eval=TRUE------------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
## ----table-weightedpct-example3, eval=TRUE------------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
## ----table-weightedpct-example4, eval=TRUE------------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
## ----table-weightedpct-example5, eval=TRUE------------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
)
## ----table-weightedpct-example5b, eval=TRUE-----------------------------------
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
) %>%
pivot_wider(names_from = disability_cat, values_from = problems)
## ----table-unweightedpctn-example, eval=TRUE----------------------------------
table_unweightedpctn(df_adults_noNA,
vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"),
group_by_var = "disability_cat",
spread_by_group_by_var = TRUE)
## ----table-basicstats-example, eval=TRUE--------------------------------------
table_basicstats(df_adults_noNA, "HHID", "age_cat")
## ----plot-pop-pyramid, eval=TRUE, echo=FALSE----------------------------------
include_graphics("Images/pop_pyramid.png")
## ----plot-distribution, eval=TRUE, echo=FALSE---------------------------------
include_graphics("Images/distribution.png")
## ----plot-density, eval=TRUE, echo=FALSE--------------------------------------
include_graphics("Images/density.png")
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c6_after_rasch_ES.R
|
---
title: "6 - Después de Análisis Rasch: Análisis descriptivo"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{6 - Después de Análisis Rasch: Análisis descriptivo}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
library(tidyr)
library(dplyr)
library(whomds)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>",
survey.lonely.psu = "adjust")
```
# Unir puntajes con datos originales
Una vez que haya terminado con Rasch Analysis, la puntuación se genera en el archivo `Data_final.csv` en la columna llamada `rescaled`. Este archivo solo contendrá los individuos incluidos en el análisis. Cualquier persona que tenga demasiados valores perdidos (`NA`) no estará en este archivo. A menudo es recomendable combinar los datos originales con todos los individuos con las nuevas puntuaciones. Cualquier persona que no haya calculado una puntuación tendrá un `NA` en esta columna.
Esta unión se puede lograr con el siguiente código. Primero, abre el paquete llamada `tidyverse` para acceder a las funciones necesarias. A continuación, lee el archivo `Data_final.csv` y selecciona solo las columnas que necesitas: `ID` (o cualquiera que sea el nombre de la columna de identificación individual en sus datos) y `rescaled`. El siguiente código asume que el archivo está en su directorio operativo. Tendrás que incluir la ruta completa al archivo si no está actualmente en su directorio operativo. Finalmente, puedes crear un objeto `merged_data` que fusione sus datos originales, aquí representados con el objeto `original_data`, con la nueva puntuación en una columna renombrada a `"DisabilityScore"` con el siguiente código:
```{r join-example}
library(tidyverse)
new_score <- read_csv("Data_final.csv") %>%
select(c("ID", "rescaled"))
merged_data <- original_data %>%
left_join(new_score) %>%
rename("DisabilityScore" = "rescaled")
```
Los datos de ejemplo incluidos en el paquete `whomds` llamado `df_adults` ya tienen una puntuación de Rasch combinada, en la columna `disability_score`.
# Después de Rasch: análisis descriptivo
Después de calcular los puntajes de discapacidad con el Análisis Rasch, ahora estás listo para analizar los resultados de la encuesta mediante el cálculo de estadísticas descriptivas. El paquete `whomds` contiene funciones para crear tablas y figuras de estadísticas descriptivas. Esta sección repasará estas funciones.
## Tablas
Las funciones de estadísticas descriptivas incluidas en el paquete `whomds` son:
* `table_weightedpct()` - produce tablas ponderadas de N o %
* `table_unweightedpctn()` - produce tablas no ponderadas de N y %
* `table_basicstats()` - calcula estadísticas básicas del número de miembros por grupo por hogar.
Los argumentos de cada uno de estos códigos se describirán a continuación.
### `table_weightedpct()`
`whomds` contiene una función llamada `table_weightedpct ()` que calcula las tablas de resultados ponderados de la encuesta, desagregadas por variables especificadas. Los argumentos de esta función se pasan a funciones en el paquete `dplyr`.
A continuación se presentan los argumentos de la función:
* `df` - el marco de datos con todas las variables de interés
* `vars_ids` - nombres de variables de los identificadores de cluster de encuesta
* `vars_strata` - nombres de variables de los estratos de la encuesta
* `vars_weights` - nombres de variables de los ponderaciones
* `formula_vars` - vector de los nombres de columna de las variables para las que desea imprimir los resultados
* `...` - captura expresiones para filtrar o transmutar los datos. Vee la descripción del argumento `willfilter` a continuación para más detalles.
* `formula_vars_levels` - vector numérico de los niveles de factor de las variables en `formula_vars`. Por defecto, la función asume que las variables tienen dos niveles: 0 y 1
* `by_vars` - las variables por las que desagregas
* `pct` - una variable lógica que indica si se deben calcular o no los porcentajes ponderados. El valor predeterminado es `TRUE` para porcentajes ponderados. Ajuste a `FALSE` para N ponderada
* `willfilter` - una variable que le dice a la función si filtrarás o no los datos por un valor particular.
+ Por ejemplo, si sus `formula_vars` tienen opciones de respuesta de 0 y 1 pero solo quieres mostrar los valores para 1, entonces diría que `willfilter = TRUE`. Luego, al final de la lista de argumentos, escribe una expresión para el filtro. En este caso, dirías `resp == 1`.
+ Si es `willfilter = FALSE`, entonces la función asumirá que desea "transmutar" los datos, en otras palabras, manipular las columnas de alguna manera, lo que para nosotros a menudo significa combinar las opciones de respuesta. Por ejemplo, si sus `formula_vars` tienen 5 opciones de respuesta, pero solo desea mostrar los resultados para la suma de las opciones `"Agree"` y `"StronglyAgree"`, (después de configurar `spread_key = "resp"` para extender el tabla por las opciones de respuesta) podrías escribir `willfilter = FALSE`, y luego directamente después de escribir la expresión para la transmutación, dándole un nuevo nombre de columna; en este caso, la expresión sería` NewColName = Agree + AgreeStrongly`. También escribe los nombres de las otras columnas que te gustaría mantener en la tabla final.
+ Si deja `willfilter` como su valor predeterminado de `NULL`, la función no filtrará ni transmutará los datos.
* `add_totals`: una variable lógica que determina si se crean filas o columnas totales (según corresponda) que demuestren el margen que suma a 100. Manténlo como el valor predeterminado `FALSE` para no incluir los totales.
* `spread_key` - la variable para la que extiendas la tabla horizontalmente. Mantén como predeterminado `NULL` para no extender la tabla horizontalmente.
* `spread_value` - la variable con la que se llena la tabla después de una extensión horizontal. Por defecto, este argumento es `"prop"`, que es un valor creado internamente por la función y generalmente no necesita ser cambiado.
* `arrange_vars` - la lista de variables para la que organizas la tabla. Mantén como predeterminado `NULL` para dejar el arreglo como está.
* `include_SE` - una variable lógica que indica si se deben incluir los errores estándar en la tabla. Mantén como predeterminado `FALSE` para no incluir errores estándar. A partir de esta versión de `whomds`, no funciona si incluyes totales (`add_totals` es `TRUE`), extensión (`spread_key` no es `NULL`) o transmutación (`willfilter` es `FALSE`).
Aquí hay algunos ejemplos de cómo se usaría `table_weightedpct()` en la práctica. No todos los argumentos se establecen explícitamente en cada ejemplo, lo que significa que se mantienen como sus valores predeterminados.
#### Ejemplo 1: tabla larga, un nivel de desagregación
Digamos que queremos imprimir una tabla del porcentaje de personas en cada nivel de discapacidad que dieron cada opción de respuesta para un conjunto de preguntas sobre el entorno general. Escribiríamos los argumentos de `table_weightedpct()` de esta manera, y las primeras filas de la tabla se verían así:
```{r table-weightedpct-example1, eval=TRUE}
#Quitar NAs de la columna utilizada para el argumento by_vars
df_adults_noNA <- df_adults %>%
filter(!is.na(disability_cat))
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = NULL,
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
```
La tabla de resultados tiene 4 columnas: la variable por la que desagregamos los datos (`disability_cat`, es decir, el nivel de discapacidad), el elemento (`item`), la opción de respuesta (`resp`) y la proporción (`prop`).
#### Ejemplo 2: tabla ancha, un nivel de desagregación
Esta larga tabla del ejemplo anterior es excelente para el análisis de datos, pero no excelente para leer a simple vista. Si queremos hacerlo más bonito, lo convertimos a "formato ancho" mediante "extensión" mediante una variable particular. Tal vez queremos extender por `disability_cat`. Nuestra ejecución de `table_weightedpct()` ahora se vería así, y la tabla de salida sería:
```{r table-weightedpct-example2, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
```
Ahora podemos ver que nuestra columna `prop` se ha extendido horizontalmente para cada nivel de` disability_cat`.
#### Ejemplo 3: tabla amplia, un nivel de desagregación, filtrado
Quizás, sin embargo, solo nos interesan las proporciones de la opción de respuesta más extrema de 5. Ahora podríamos agregar un filtro a nuestra ejecución a `table_weightedpct()` así:
```{r table-weightedpct-example3, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
```
Ahora puede ver que solo se dan las proporciones para la opción de respuesta de 5.
#### Ejemplo 4: tabla ancha, múltiples niveles de desagregación, filtrada
Con `table_weightedpct()`, también podemos agregar más niveles de desagregación editando el argumento `by_vars`. Aquí produciremos la misma tabla que en el Ejemplo 3 anterior, pero ahora desagregada por nivel de discapacidad y sexo:
```{r table-weightedpct-example4, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
```
#### Ejemplo 5: tabla ancha, niveles múltiples de desagregación, transmutada
Quizás todavía estamos interesados no solo en la opción de respuesta 5, sino en la suma de 4 y 5 juntos. Podemos hacer esto "transmutando" nuestra tabla. Para hacer esto, primero elegimos "extender" por `resp` configurando `spread_key = "resp"`. Esto convertirá la tabla a un formato ancho como en el Ejemplo 2, pero ahora cada columna representará una opción de respuesta. Luego configuramos la transmutación estableciendo `willfilter = FALSE`, y agregando expresiones para la transmutación en la siguiente línea. Nombramos todas las columnas que nos gustaría mantener y damos una expresión de cómo crear la nueva columna de la suma de proporciones para las opciones de respuesta 4 y 5, aquí llamada "problemas":
```{r table-weightedpct-example5, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
)
```
Si nos gustaría modificar la tabla nuevamente para que `disability_cat` represente las columnas nuevamente, podemos incluir esta tabla en otra función que realizará el "pivot". La función para extender tablas se llama `pivot_wider()`, y está en el paquete `tidyr`. Para realizar una segunda extensión, escribe el código así:
```{r table-weightedpct-example5b, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
) %>%
pivot_wider(names_from = disability_cat, values_from = problems)
```
El argumento `names_from` de la función `pivot_wider()` le dice a `R` qué variable usar como columnas, y `values_from` le dice a` R` con qué llenar las columnas. El operador `%>%` se conoce comúnmente como una _"pipe"_. Pone el objeto anterior en el primer argumento de la función posterior. Por ejemplo, si tiene un objeto `x` y una función `f`, escribir `x %>% f ()` sería el equivalente a escribir `f(x)`. Las personas usan _"pipes"_ porque hacen que las secuencias largas de código sean más fáciles de leer.
### `table_unweightedpctn()`
`whomds` contiene una función llamada `table_unweightedpctn()` que produce tablas no ponderadas de N y %. Esto se utiliza generalmente para tablas demográficas. Sus argumentos son los siguientes:
* `df` - el marco de datos con todas las variables de interés
* `vars_demo` - vector con los nombres de las variables demográficas para las que se calcularán N y %
* `group_by_var`: nombre de la variable en la que se deben estratificar las estadísticas (por ejemplo, `"disability_cat"`)
* `spread_by_group_by_var` - determina lógicamente si se debe extender la tabla mediante la variable dada en `group_by_var`. El valor predeterminado es `FALSE`.
* `group_by_var_sums_to_100` - determina lógicamente si los porcentajes suman 100 en el margen de `group_by_var`, si corresponde. El valor predeterminado es `FALSE`.
* `add_totals`: una variable lógica que determina si se crean filas o columnas totales (según corresponda) que demuestren el margen que suma 100. Manténlo como el valor predeterminado `FALSE` para no incluir los totales.
Aquí hay un ejemplo de cómo se usa:
```{r table-unweightedpctn-example, eval=TRUE}
table_unweightedpctn(df_adults_noNA,
vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"),
group_by_var = "disability_cat",
spread_by_group_by_var = TRUE)
```
### `table_basicstats()`
La función `table_basicstats()` calcula estadísticas básicas del número de miembros por grupo por hogar. Sus argumentos son:
* `df` - un marco de datos de datos de hogares donde las filas representan miembros de los hogares en la muestra
* `hh_id` - cadena (longitud 1) que indica el nombre de la variable en `df` que identifica hogares únicamente
* `group_by_var` - cadena (longitud 1) con el nombre de la variable en `df` para la que se agrupa los resultados
Aquí hay un ejemplo de cómo se usa:
```{r table-basicstats-example, eval=TRUE}
table_basicstats(df_adults_noNA, "HHID", "age_cat")
```
## Figuras
Las funciones de las estadísticas descriptivas incluidas en el paquete `whomds` son:
* `fig_poppyramid()` - produce una figura de pirámide de población para la muestra
* `fig_dist()` - produce un gráfico de la distribución de una puntuación
* `fig_density()` - produce un gráfico de la densidad de una puntación
Los argumentos de cada uno de estos códigos se describirán a continuación.
### `fig_poppyramid()`
`whomds` contiene una función llamada `fig_poppyramid()` que produce una figura de pirámide de población para la muestra. Esta función toma como argumentos:
* `df` - los datos donde cada fila es un miembro del hogar de la lista del hogar
* `var_age` - el nombre de la columna en `df` con las edades de las personas
* `var_sex` - el nombre de la columna en `df` con los sexos de las personas
* `x_axis` - una cadena que indica si se deben usar números absolutos o porcentaje de muestra en el eje horizontal. Las opciones son `"n"` (predeterminado) o `"pct"`.
* `age_plus` - un valor numérico que indica la edad que es el primer valor del grupo de edad más antiguo. El valor predeterminado es 100, para el último grupo de edad de 100 o más.
* `age_by` - un valor numérico que indica el ancho de cada grupo de edad, en años. El valor predeterminado es 5.
Ejecutar esta función produce una figura como la siguiente:
```{r plot-pop-pyramid, eval=TRUE, echo=FALSE}
include_graphics("Images/pop_pyramid.png")
```
### `fig_dist()`
`whomds` contiene una función llamada `fig_dist()` que produce un gráfico de la distribución de una puntuación. La OMS utiliza esta función para mostrar la distribución de las puntuaciones de discapacidad calculadas con el Análisis de Rasch. Sus argumentos son:
* `df` - marco de datos con la puntuación de interés
* `score` - variable de carácter del nombre de variable de puntuación que va de 0 a 100; ej. `"disability_score"`
* `score_cat` - variable de carácter del nombre de variable de categorización de puntuación, ej. `"disability_cat"`
* `cutoffs` - un vector numérico de los puntos de corte para la categorización de puntuación
* `x_lab` - una cadena que da la etiqueta del eje horizontal. El valor predeterminado es `"Score"`
* `y_max` - valor máximo para usar en el eje vertical. Si se deja como predeterminado `NULL`, la función calculará un máximo adecuado automaticamente.
* `pcent` - variable lógica que indica si se debe usar el porcentaje en el eje y o la frecuencia. Deje por defecto `FALSE` para la frecuencia y dé `TRUE` para el porcentaje.
* `pal` - una cadena que especifica el tipo de paleta de colores a usar, que se pasa a la función `RColorBrewer::brewer.pal()`. El valor predeterminado es `"Blues"`.
* `binwidth` - un valor numérico que da el ancho de los contenedores en el histógrafo. El valor predeterminado es 5.
Ejecutar esta función produce una figura como la de abajo.
```{r plot-distribution, eval=TRUE, echo=FALSE}
include_graphics("Images/distribution.png")
```
### `fig_density()`
`whomds` contiene una función similar a `fig_dist()` llamada `fig_density()` que produce un gráfico de la densidad de una puntuación. La OMS utiliza esta función para mostrar la distribución de densidad de las puntuaciones de discapacidad calculadas con el Análisis de Rasch. Sus argumentos son:
* `df` - marco de datos con la puntuación de interés
* `score` - variable de carácter del nombre de variable de puntuación que va de 0 a 100; ej. `"disability_score"`
* `var_color` - variable de carácter con el nombre de la columna que se usa para determinar los colores de las líneas de densidad. Se usa este variable para imprimir las densidades de diferentes groups en el mismo gráfico. El valor predeterminado es `NULL`.
* `var_facet` - variable de carácter con el nombre de la columna que se usa para crear un gráfico con `ggplot2::facet_grid()`, que se imprime las densidades de diferentes groups lado a lado. El valor predeterminado es `NULL`.
* `cutoffs` - un vector numérico de los puntos de corte para la categorización de puntuación
* `x_lab` - una cadena que da la etiqueta del eje horizontal. El valor predeterminado es `"Score"`
* `pal` - una cadena que especifica un color manual para utilizar para el aestitico del color, un vector de carácter que especifica los colores que se usa para la escala de colores, o como el tipo de paleta de colores a usar para la escala de colores, que se pasa a la función `RColorBrewer::brewer.pal()`. El valor predeterminado es `"Paired"`
* `adjust` - un valor numérico que se pasa al argumento `adjust` de `ggplot2::geom_density()`, que suaviza la función de la densidad. El valor predeterminado es 2.
* `size` - un valor numérico que se pasa al argumento `size` de `ggplot2::geom_density()`, que controla el espesor de las líneas. El valor predeterminado es 1.5.
Ejecutar esta función produce una figura como la de abajo.
```{r plot-density, eval=TRUE, echo=FALSE}
include_graphics("Images/density.png")
```
## Plantillas para estadísticas descriptivas
La OMS también proporciona una plantilla para calcular muchas tablas de estadísticas descriptivas para su uso en informes de encuestas, también escritas en `R`. Si desea una plantilla para su país, contáctenos (por favor abre el archivo DESCRIPTION para obtender los detalles de contacto).
|
/scratch/gouwar.j/cran-all/cranData/whomds/inst/doc/c6_after_rasch_ES.Rmd
|
---
title: "1 - Background on disability measurement"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{1 - Background on disability measurement}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(whomds)
options(survey.lonely.psu = "adjust")
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Introduction
## Background
In light of calls for sound and comprehensive disability data the Model Disability Survey (MDS) project was initiated by WHO and the World Bank (WB) in 2011.
The MDS is grounded in the International Classification of Functioning, Disability and Health (ICF) and represents an evolution in the concept of disability measurement. It explores disability as the experience of a person with a health condition or impairment encountering a facilitating or hindering environment, instead of solely focusing on the individual's health status.
In keeping with the conceptual framework of the ICF, the MDS takes the approach that:
* Disability is not an internal attribute of a person but an experience;
* Disability is etiologically neutral;
* Disability is a continuum, a quantity, and a matter of degree, ranging from no disability to extreme disability;
* Disability is universal, meaning every person sits somewhere on the disability continuum.
The rationale behind the MDS requires therefore a general population sample and the use of no filters, i.e. no _a priori_ selection of respondents, with three main goals:
* Achieving comparable and standardized disability prevalence rates across countries;
* Delivering the needed data for designing appropriate interventions, programs and policies for persons with mild, moderate and severe levels of disability;
* Monitoring the implementation of the Sustainable Development Goals (SDGs) and the United Nation Convention on the Rights of Persons with Disabilities (CRPD) by allowing for a direct comparison among persons with mild, moderate and severe levels of disability, and persons with no disability.
The MDS takes the approach that disability is a universal phenomenon characterized by a continuum ranging from low to high disability levels. This conceptualization requires information on disability to be reported and analyzed using metrical scales. This scale will range from 0 (no disability) to 100 (extreme disability).
Following an approach similar to the one of the World Report on Disability (WRD) and using modern test theory, functioning questions of Module 4000 are used to build a disability scale with metric properties. The whole general population sample is used to create this metric, which is then linearly transformed to range from 0 (lowest level of disability) to 100 (highest level).
## Purpose of this guide
The WHO Disability Programme offers technical support to countries to guide successful implementation of the survey and to analyze the resulting data. This guide is part of this package of technical support.
To create the disability scale, on which every individual in the same has a score from 0 to 100, WHO uses a technique called Rasch Analysis. The purpose of this guide is to explain in detail how Rasch Analysis is done and how to use the WHO package of codes, written in the statistical programming language `R`, in order to carry out the Rasch Analysis for the MDS.
## Objectives
1. Understand measurement and the information that different kinds of scales can provide;
2. Describe the reasoning and process behind Rasch Analysis;
3. Learn how to prepare data for a Rasch model;
4. Learn how to run a Rasch model;
5. Learn how to assess the quality of the Rasch model;
6. Learn how to adjust data to improve the quality of a Rasch model;
7. Understand how to use the package to calculate descriptive statistics.
# What is measurement?
At first glance, measurement seems very straight forward. However, the concept of "measurement" is actually made up of a few smaller components. It is important to understand each of these components when formulating any new measurement tool, like we are doing with the Model Disability Survey.
The main ideas of measurement are as follows:
* **Objects** have **properties** that can be thought in terms of more or less, larger or smaller, stronger or weaker.
* This **property** can be measured through its **manifestation** (or observable behavior).
* This **manifestation** can be mapped onto a **scale**.
* **Measurement** can have some **error** involved, and may not be perfectly precise.
For example, a person (**object**) has a certain intelligence regarding mathematics (**property**). This person's mathematical intelligence can be observed via their performance on a math test (**manifestation**). Their performance on the math test is given a score from 0 to 100 (**scale**). The score someone receives on a particular day can be influenced by random factors like their mood or the conditions of the room, so the score may not exactly reflect the person's true intelligence (**error**).
Just as there are different types of **properties** that objects can have (for example: height, weight, color, intelligence), there are also different types of **scales** that these properties can be measured with. Each of these different types of scales can give you different types of information, and you can only perform certain types of mathematical operations with each type of scale.
The four main types of scales are:
* **Nominal scale** - This scale involves assigning names to objects. For example, on a survey we often identify people as "Male" or "Female". This would be considered a nominal scale. The only mathematical operation available for this scale is assessment of equality. In other words, with nominal scales, you can only determine if two objects are the same or they are not.
* **Ordinal scale** - This scale involves placing objects in a particular order. For example, on a survey you often have questions with response options as follows: "Disagree strongly", "Disagree", "Neither agree nor disagree", "Agree", and "Agree strongly". This would be an ordinal scale. There are two mathematical operations possible with ordinal scales: equality and more/less. For example, with this scale you can determine if two objects give equal responses (for example, two people both answer "agree" to a question on a survey) or if one person's answer is "greater" than another's. For example, if Person A answers "agree" and Person B answers "agree strongly", you can be certain that Person B agrees more to the item than Person A. However, you cannot determine the "distance" between items. In other words, taking our example, you do not know _how much more_ Person B agrees than Person A.
* **Interval scale** - This scale involves placing objects at positions that have meaningful order and distance relative to other objects. For example, the weather on two days can have two different temperatures. Let's say Day 1 has a temperature of 10 degrees Celsius and Day 2 has a temperature of 20 degrees Celsius. This is an example of an interval scale. With this scale, we can use three different mathematical operations: we can determine if two objects are equal, if one is greater than another, and also the relative distance between them. In our example, clearly Day 1 and Day 2 have two different temperatures, and Day 2 is hotter than Day 1. But even more than that, we can say that Day 2 is exactly 10 degrees Celsius hotter than Day 1. Unlike with an ordinal scale, the distance between two points on the scale is meaningful. However, we cannot determine ratios between two points on the scale. In our example, we cannot say that Day 2 was twice as hot as Day 1. This is because 0 degrees Celsius is arbitrarily placed. When it is 0 degrees outside, it is cold, but there still is a temperature present.
* **Ratio scale** - This scale is like an interval scale, except that it also has a meaningful "0" point. We can apply four different mathematical operations to this scale: the three from an interval scale in addition to multiplication/division. For example, imagine Person A is 100cm tall and Person B is 150cm tall. Clearly we can determine that Person A is not the same height as Person B, Person A is shorter than Person B, and Person A is 50cm shorter than Person B. But even more than that, because 0cm is meaningful, we can say that Person B is 50% taller than Person A. We can create a ratio between their heights. Unlike with temperature, we can say for certain where 0cm is--if something is 0cm tall, then it's not there!
The table below gives a summary of what kind of information is possible with each scale.
```{r plot-scales, eval=TRUE, echo=FALSE}
include_graphics("Images/scales.png")
```
Most of the questions of the MDS are on a 5-point ordinal scale (for example, 1=None, 2=Some, 3=Moderate, 4=A lot, 5=Complete). In order to create a score we can use and trust, what we want to do is **take our ordinal data and map it onto an interval scale** of disability. In other words, using the ruler below as a reference, we want to move from the top of the ruler to the bottom.
```{r plot-ruler, eval=TRUE, echo=FALSE}
include_graphics("Images/ruler.png")
```
Why is simply adding up ordinal data not good enough? Imagine you are the CEO of a company that sells orange juice. You ask your employees, how much orange juice will we be able to produce this quarter? Employee A replies that the company has produced **5000 oranges** while Employee B replies that the company has produced **1500kg of oranges**. Who gave you the most information about how much orange juice you will be able to produce?
Employee B gave you information on an interval scale (weight), and Employee A gave you information on an ordinal scale (count). Employee B gave you more information; with her answer you know precisely how much orange juice you have to sell. Employee A told you how many oranges you have, but you have no idea how big or small they are.
```{r plot-oranges, eval=TRUE, echo=FALSE}
include_graphics("Images/oranges.png")
```
This scenario is similar to our questionnaire. We could just simply add up all answers to all the questions we are interested in to calculate a sum score. However, that sum score doesn't tell us much about the overall level of disability a person experiences, because we don't know which questions were identified as difficult, and different questions have different levels of difficulty.
For example, imagine that a person is answering questions from the Model Disability Survey. This person answered "3=Some problems" to both questions, "How much of a problem is toileting?" and "How much of a problem do you have with sleep?". One can imagine that difficulties with sleep are fairly common, and many of us experience problems with sleep without it impacting our lives too much. However, many fewer people have "some problems" with using the toilet, and one can imagine that having even some level of difficulty with using the toilet can cause significant problems in someone's life. Therefore, one can see that the answer of "3" to "sleep" is not equivalent to the "3" answered to "toileting".
So, in essence, we are trying to move from counting responses to questions about disability to truly measuring levels of disability on an interval scale. We will do this using **Rasch Analysis**.
# How does an interval scale apply to measuring disability?
Before we begin discussion of the technique of Rasch Analysis, it is important to emphasize again WHO's understanding of disability. We are measuring disability on an **interval scale**. This scale ranges from 0 (no disability) to 100 (extreme disability), and every person in the population sits somewhere on the scale.
This is quite different from the traditional way of thinking about disability. Often, when people hear the word "disability" they think of different "types of disabilities", and the people that most quickly come to mind are, for instance, people who are blind, people who are deaf, or people who use wheelchairs. For WHO, the word "disability" does not refer to attributes of specific, narrow groups of people who have particular impairments. For WHO, "disability" refers to a universal experience--not an attribute of a person--which is the outcome of a multitude of factors, like an underlying health condition or the accessibility of an environment.
As an example, take one person who has a vision impairment due to glaucoma and another person who has a mobility impairment due to a spinal cord injury. Both people may have difficulty using the transportation system. The person with a vision impairment may have difficulty using transportation because the names of the stops on the bus are not announced over the loud speaker, so the person cannot tell when she has reached her destination. The person with the mobility impairment may have difficulty using the transportation system because the buses do not have ramps that would allow her to alight independently with her wheelchair. Despite the fact that these two people have different types of impairments and run into different types of barriers, the _level of disability_ they experience is quite similar in this particular domain of transportation.
The output of Rasch Analysis will give us the disability score for each person in the sample. We can then plot these scores in a histogram to get an overall picture of the distribution of disability in a population. An example of such a distribution is below. You can think of the horizontal axis as a ruler. Each person sits somewhere on this ruler, and the heights of the bars tells how many people are at that particular position on the ruler.
```{r plot-distributionruler, eval=TRUE, echo=FALSE}
include_graphics("Images/distributionruler.png")
```
# Why should we use Rasch Analysis?
## Important properties
The main reason why we use Rasch Analysis has already been mentioned: it allows us to take ordinal data and map it onto an interval scale. However there are other important properties of the Rasch Model that make it a particularly useful method for our purposes:
* No assumptions are made about distribution of person abilities
* Difficulties of two items can be compared independently of abilities of the persons
* Abilities of two people can be compared independently of difficulties of items
* The difference between person abilities and item difficulties is a _sufficient statistic_ (see a statistical text for more information about sufficient statistics)
## Goals
Ultimately we have three main goals when performing Rasch Analysis:
1. Obtain person ability estimates
2. Know the difficulty of items on the scale
3. Create and **validate** an interval-scaled **reliable** measurement tool
Goal 1, in other words, gives us the disability scores we are looking for. Goal 2 tells us how "difficult" items are, meaning how indicative of different levels of disability (mild, moderate, severe) they are.
Goal 3 has to do with the psychometric properties of the survey instrument we are using. With Rasch Analysis, in addition to calculating the interval scale, we are simultaneously performing an analysis of the validity and reliability of the scale. If our data fit the model property, then we can be certain that the scores that we obtain for people and for items are valid (i.e., they are measuring what we intend for them to measure) and reliable (i.e., the survey instrument would give consistent results if the survey was repeated).
## Output
As already mentioned above, one of our aims is to obtain the person ability estimates. This means that an output of the Rasch analysis will be a latent trait continuum (shown below)...
```{r plot-continuum, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum.png")
```
...where you can locate specific people...
```{r plot-continuum-person, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum_person.png")
```
...and also the items!
```{r plot-continuum-personitem, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum_personitem.png")
```
"Latent trait continuum" is another phrase to describe the scale. "Latent trait" refers to an underlying characteristic of the population that the survey instrument is measuring (in our case, disability). "Continuum" is simply another word for "scale", emphasizing that people can be placed at any point between the end points (0 and 100) of the scale.
The figure above is illustrating a toy example analyzing the strength of people and the difficulty of each item (questions Q1 to Q10) in regards to strength. The strongest person is on the left side of the continuum, while the weakest person is on the right side of the continuum. We can see that items Q9 and Q10 are the easiest; they are located on the same end of the continuum as the weakest person. The probability that the strongest people on the left end of the continuum get the questions "correct" is very high. Questions Q1 and Q2 are the hardest; only the strongest people, located on the same end of the continuum, have a reasonable probability of getting these questions "correct."
# What is Rasch Analysis?
Rasch Analysis was named after Danish mathematician Georg Rasch (1901-1980). The fundamental idea of Rasch Analysis was summarized by Rasch as follows:
> ...a person having a greater ability than another person should have the greater probability of solving any item of the type in question, and similarly, one item being more difficult than another means that for any person the probability of solving the second item is the greater one.
This quote from Rasch refers to two situations:
1. If we have two people, Person A and Person B, and Person A has more disability than Person B, then Person A has a greater probability of rating any given item on the survey, for instance "walking 100m," as more difficult than Person B.
2. If we have two items, Item A and Item B, and Item A is more difficult than Item B, then any given person will have a higher probability of rating Item A as more difficult than Item B.
Rasch is one of the simplest models in **Item Response Theory (IRT)**. IRT is a **probabilistic** approach to measurement: the probability of a "correct" response to an item (i.e., question) is a function (i.e., relationship) of the parameters (i.e., characteristics) the person and the item.
Under the Rasch Model, the probability of a certain response to a measurement item is associated with the respondent's ability ($\beta_n$) and the item's difficulty ($\delta_i$). Using our previous example of a mathematics test, the person's ability $\beta_n$ would be the person's mathematical intelligence, and the item's difficulty $\delta_i$ would be the difficulty of any given question on the test.
There are two different versions of the model: the dichotomous version (all questions have two response options, for instance 0 and 1) and the polytomous version (questions have more than 2 response options). The polytomous model, which we are most interested in because in the MDS most questions use a 5-point scale ranging from "1=No problems" to "5=Extreme problems", is simply an extension of the dichotomous version. Below we give a basic overview of the models.
## The Rasch Model - Dichotomous
Below is the main equation for the dichotomous Rasch Model (two response options):
$$P(X_{ni}=1) = \frac{e^{\beta_n-\delta_i}}{1+e^{\beta_n-\delta_i}}$$
where
* $i$ - item counter
* $n$ - person counter
* $X_{ni}$ - random variable of score of person $n$ on item $i$
* $\beta_n$ - location of person $n$ on latent continuum
* $\delta_i$ - difficulty of item $i$ on latent continuum
In simpler terms, this means: the **probability** that person $n$ gets question $i$ correct is a **ratio** based on the difference between that person's ability ($\beta_n$) and the difficulty of that item ($\delta_i$).
This can be seen in the following figure. The vertical axis is the probability of the person getting a question correct ($P(X_{ni}=1)$), ranging from 0 to 1. The horizontal axis is the difference between a person's ability and the item difficulty ($\beta_n-\delta_i$). Let us say that this question has two options: 0 and 1, and a "correct" response to the item is the response option of 1. When the person's ability and the item difficulty are equal ($\beta_n-\delta_i=0$ or $\beta_n=\delta_i$), then the probability that the person gets the question correct is 50%. If the person's ability is higher than the item difficulty ($\beta_n > \delta_i$), then the probability that the person gets the question correct is greater than 50%. If the person's ability is less than the item difficulty ($\beta_n < \delta_i$), then the probability that the person gets the question correct is less than 50%.
``` {r rasch-setup, echo=FALSE, eval=TRUE, out.width = NULL}
x <- seq(-5,5,0.01)
y <- exp(x)/(1+exp(x))
df <- tibble(x,y)
ggplot(df,aes(x=x,y=y)) +
geom_point() +
labs(x="Difference between person ability\n and item difficulty", y="Probability of person getting\n question correct")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
```
## The Rasch Model - Polytomous
The polytomous Rasch Model (more than 2 response options) is an extension of the dichotomous version. It is also known as the **Partial Credit Model**. The main equation for this model is:
$$P(X_{ni}=x) = \frac{e^{\sum^x_{k=0}(\beta_n-\tau_{ki})}}{\sum^{m_i}_{j=0}e^{\sum^j_{k=0}(\beta_n-\tau_{ki})}}$$
where
* $i$ - item counter
* $n$ - person counter
* $X_{ni}$ - random variable of score of person $n$ on item $i$
* $\beta_n$ - location of person $n$ on latent continuum
* $\tau_{ki}$ - $k^{th}$ threshold of item $i$ on latent continuum
* $m_i$ - maximum score for item $i$
In simpler terms, the **probability** that person $n$ gives answer $x$ to question $i$ is a **ratio** based on the difference between that person's ability ($\beta_n$) and the difficulty of each response option ($\tau_{ki}$) for that item.
This can be seen in the following figure, which is similar to the figure for the dichotomous model. The vertical axis is the conditional probability of the person achieving choosing a particular response option or higher ($P(X_{ni}>x)$), ranging from 0 to 1. The horizontal axis is the difference between a person's ability and the item difficulty. The key difference between this figure and the figure for the dichotomous model is that now we have a probability curve for each threshold.
A **threshold** is the point between two adjacent response options where a person has a 50% chance of giving one response option or another. The figure below shows the case of four response options, which means this question has three thresholds (The 50% point between response options 1 and 2, the same point between options 2 and 3, and the same point between options 3 and 4).
In the figure below, you can see that the probability of passing the first threshold (red curve), in other words achieving a score of 2, is always higher than the probability of passing the second (green) or third (blue) threshold. This shows a key property of the polytomous Rasch Model: thresholds are **ordered**.
``` {r rasch-setup-poly, echo=FALSE, eval=TRUE, out.width = NULL}
x <- seq(-5,5,0.01)
tao <- c(-2.5,0,2.5)
y0 <- exp(x-tao[1])/(1+exp(x-tao[1]))
y1 <- exp(x-tao[2])/(1+exp(x-tao[2]))
y2 <- exp(x-tao[3])/(1+exp(x-tao[3]))
df <- tibble(x,y0,y1,y2)
df.long <- df %>%
pivot_longer(!x, names_to = "Threshold", values_to = "y")
ggplot(df.long,aes(x=x,y=y,color=Threshold)) +
geom_point()+
scale_color_discrete(labels=c("First","Second","Third")) +
labs(x="Difference between person ability\n and item difficulty", y="Conditional probability of person\n passing response threshold")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
```
# How do you do Rasch Analysis?
## Overview of the method
Everything we have described so far is background to the rationale of Rasch Analysis. However at this point we have not yet described how it is actually done.
Overall, the basic technique is to **fit our data to the Rasch Model**, taking note of how well it fits the **Rasch Model assumptions**. This differs from other types of modeling where you _fit a model to your data_. The Rasch Model is seen as the "ideal", and we want to adjust our data in such a way that it can fit this ideal. If our data can reasonably fit this ideal, then we can be assured we have a **valid** and **reliable** interval scale.
Rasch Analysis is an **iterative process**, meaning it must be performed multiple times in order to reach a result. The process is shown in the figure below.
``` {r iteration, echo=FALSE, eval=TRUE}
include_graphics("Images/iteration_EN.png")
```
The next question naturally is: what are the Rasch assumptions that we are testing?
## Rasch assumptions
The Rasch Model assumptions are as follows. Each assumption will be discussed in detail in the following sections:
1. Item independence
2. Unidimensionality
3. Stochastic ordering
4. Group invariance
5. Fit to model
We will also discuss below how to adjust data to have it better fit each assumption. These techniques might not make much sense now, but they will become clearer once we go through the example.
### Item independence
Item independence refers to uncorrelation between items. In other words, we want responses to one item to NOT be related strongly with responses in another item. Correlation happens when items are linked by common attributes, content, structures, or themes. For example, in the MDS two items that are often related are "How much of a problem do you have with feeling sad, low or depressed?" and "How much of a problem do you have with feeling worried, nervous or anxious?"
In order to take care of problems with high correlation, we often aggregate dependent items into one "super item", or "testlet". For instance if we have two items, each with 5 response options, that are highly correlated, we could combine them into a testlet by adding up the responses for each person. This testlet would now have 9 response options.
### Unidimensionality
Unidimensionality refers to the situation when all items measure the same underlying single construct. In the case of the MDS, we want all items to be measuring the same underlying construct of "disability". A total score is only meaningful with a unidimensional scale.
Take another example in the educational field: Imagine a math test. All items on this test are measuring the same underlying construct, that is, the person's ability in math. If a math test also contained English literature questions, the scale created with all the items of this test would no longer be unidimensional because the test is composed of two totally separate sets of items.
If we notice problems with the dimensionality of our data, we can correct this by splitting items onto multiple scales. In our educational example above, this would mean creating a separate scale for the math questions on the test and a separate scale for the English questions.
### Stochastic ordering
Stochastic ordering refers to the thresholds (i.e., boundaries between response options) being in the correct order. We expect the probability of a person crossing the first threshold to be higher than the probability they pass the second, and likewise the probability of crossing the second threshold should be higher than the probability of crossing the third, etc. As an analogy, think of a high jump: if someone is able to jump over 1.5m, then they necessarily already jumped over 1m. Stochastic ordering is only relevant for items with more than 2 response options (polytomous case).
```{r plot-highjump, eval=TRUE, echo=FALSE}
include_graphics("Images/highjump.jpg")
```
If we have problems with stochastic ordering, we can recode response options in order to create fewer thresholds between items that are more likely to be in order.
### Group invariance
Group invariance refers to items behaving similarly for people with different characteristics. For example, we want men and women to show similar patterns of responses for an item. If items show different behavior for different groups, this is referred to as "differential item functioning (DIF)".
For the MDS, because we expect men and women to experience different levels of disability, we are not too concerned with group invariance. This is the same for people of different ages, because the older we get, the higher the probability of experiencing disability in daily life.
If we want to correct for DIF, we can split items into subgroups. For instance instead of having one question Q1 for the whole sample, we can split it into two questions Q1_Men and Q1_Women.
### Fit to model
In addition to all the above assumptions, we also care about fit to the model. Fit of items, persons, and the model overall are measured with various fit statistics.
We determine:
* Do **items** fit the model? -> examine item fit
* Do **people** fit the model? -> examine person fit
* How is the model **overall**? -> examine reliability scores, like person separation index (PSI)
If items or people are showing poor fit to the model after making all other adjustments we could make, all that's left to do is delete items or people from the scale. This would be considered a last resort, as it means the scale you end up creating does not examine all the items or people you originally set out to measure.
## Why do I have to run the model multiple times?
It is very rare for the first model you run to give perfect results where everything fits. If your goal is simply to assess the validity and reliability of your questionnaire with the raw data, then you could run the model once and analyze those results. However if your goal is to obtain a valid and reliable score--as it is in the case of the MDS--then it is most often necessary to run the model multiple times, making adjustments to the data each time. We are trying to find a way to fit the data to the Rasch "ideal", in other words to create a score that adheres to these basic assumptions built in to the Rasch model. The fact that you must run the model multiple times does not at all necessarily mean there is something wrong with your questionnaire. The Rasch Analysis process simply tells you how best to utilize survey instrument you have to create the most trustworthy score.
## Where do I start? {#repair}
The figure below shows the repair pathway for the Rasch Model. Overall, you can see that all of these assumptions can affect the performance of other assumptions. However, general guidance about what order to use when adjusting data can be determined.
```{r plot-repair, eval=TRUE, echo=FALSE}
include_graphics("Images/repair.png")
```
Local dependency (or item independence) affects unidimensionality, threshold ordering (or stochastic ordering) and the fit to the model, so it is good to start by taking care of item independence first. Unidimensionality affects threshold ordering and the fit to the model, so it's a good assumption to take care of second. Threshold ordering affects the fit to the model, so it can be taken care of third. Finally, group invariance only affects fit to the model, so it can be taken care of last.
## How do I know when I'm done?
Determining when you can stop running iterations of the Rasch Model is not totally straightforward. There are general rules of thumb we will learn, but it takes practice to get a sense of what is "good enough". The rest of this guide will show you what to look for in order to determine when your data fits the model well enough.
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c1_background_EN.Rmd
|
---
title: "1 - Antecedentes sobre la medición de discapacidad"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{1 - Antecedentes sobre la medición de discapacidad}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(whomds)
options(survey.lonely.psu = "adjust")
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Introducción
## Antecedentes
En 2011, el proyecto de la Encuesta Modelo sobre la Discapacidad (MDS, por sus siglas en inglés) fue iniciado por la OMS y el Banco Mundial (BM) en 2011.
El MDS se basa en la Clasificación Internacional de Funcionamiento, Discapacidad y Salud (ICF, por sus siglas en inglés) y representa una evolución en el concepto de medición de la discapacidad. Explora la discapacidad como la experiencia de una persona con una condición de salud o discapacidad que se encuentra en un entorno facilitador u obstaculizador, en lugar de centrarse únicamente en el estado de salud de la persona.
En consonancia con el marco conceptual de la ICF, la MDS adopta el enfoque de que:
* La discapacidad no es un atributo interno de una persona sino una experiencia;
* La discapacidad es etiológicamente neutral;
* La discapacidad es un continuo, una cantidad y una cuestión de grado, que va desde la no discapacidad a la discapacidad extrema;
* La discapacidad es universal, lo que significa que cada persona se sienta en algún lugar del continuo de la discapacidad.
Por lo tanto, la razón detrás de la MDS requiere una muestra de población general y el uso de no filtros, es decir, no una selección a priori de los encuestados, con tres objetivos principales:
* Lograr tasas de prevalencia de discapacidad comparables y estandarizadas en todos los países;
* Entregar los datos necesarios para diseñar intervenciones, programas y políticas apropiadas para personas con niveles de discapacidad leves, moderados y graves;
* Supervisar la implementación de los Objetivos de Desarrollo Sostenible (ODS) y la Convención de las Naciones Unidas sobre los Derechos de las Personas con Discapacidad (CRPD, por sus siglas en inglés) al permitir una comparación directa entre las personas con niveles de discapacidad leves, moderados y graves, y las personas sin discapacidad.
La MDS adopta el enfoque de que la discapacidad es un fenómeno universal caracterizado por un continuo que varía de niveles de discapacidad bajos a altos. Esta conceptualización requiere que la información sobre la discapacidad se informe y analice utilizando escalas métricas. Esta escala va desde 0 (sin discapacidad) a 100 (discapacidad extrema).
Siguiendo un enfoque similar al del Informe Mundial sobre Discapacidad (WRD, por sus siglas en inglés) y utilizando la moderna teoría de pruebas, las preguntas de funcionamiento del Módulo 4000 se utilizan para construir una escala de discapacidad con propiedades métricas. La muestra de la población general se utiliza para crear esta métrica, que luego se transforma linealmente para ir desde 0 (nivel más bajo de discapacidad) hasta 100 (nivel más alto).
## Propósito de esta guía
El Programa de Discapacidad de la OMS ofrece apoyo técnico a los países para guiar la implementación exitosa de la encuesta y analizar los datos resultantes. Esta guía forma parte de este paquete de apoyo técnico.
Para crear la escala de discapacidad, en la que cada individuo tiene una puntuación de 0 a 100, la OMS utiliza una técnica llamada Análisis de Rasch. El propósito de esta guía es explicar en detalle cómo se realiza el Análisis de Rasch y cómo utilizar el paquete de códigos de la OMS, escrito en el lenguaje de programación estadística `R`, para llevar a cabo el Análisis de Rasch para el MDS.
## Los objetivos
1. Comprender la medición y la información que los diferentes tipos de escalas pueden proporcionar;
2. Describir el razonamiento y el proceso detrás del Análisis Rasch;
3. Aprender a preparar datos para un modelo de Rasch;
4. Aprender a ejecutar un modelo Rasch;
5. Aprender a evaluar la calidad del modelo de Rasch;
6. Aprender a ajustar los datos para mejorar la calidad de un modelo de Rasch;
7. Comprender cómo usar el paquete para calcular estadísticas descriptivas.
# ¿Qué es la medición?
A primera vista, la medición parece muy directa. Sin embargo, el concepto de "medición" en realidad se compone de unos pocos componentes más pequeños. Es importante entender cada uno de estos componentes al formular una nueva herramienta de medición, como lo estamos haciendo con la Encuesta Modelo sobre Discapacidad.
Las principales ideas de medición son las siguientes:
* Los **objetos** tienen **propiedades** que se pueden pensar en términos de más o menos, más grandes o más pequeños, más fuertes o más débiles.
* Esta **propiedad** puede medirse a través de su **manifestación** (o comportamiento observable).
* Esta **manifestación** se puede mapear en una **escala**.
* **Medición** puede tener algún **error** involucrado, y puede no ser perfectamente preciso.
Por ejemplo, una persona (**objeto**) tiene cierta inteligencia con respecto a las matemáticas (**propiedad**). La inteligencia matemática de esta persona se puede observar a través de su desempeño en una prueba de matemáticas (**manifestación**). Su desempeño en el examen de matemáticas recibe una puntuación de 0 a 100 (**escala**). El puntaje que alguien recibe en un día en particular puede estar influenciado por factores aleatorios como su estado de ánimo o las condiciones de la habitación, por lo que el puntaje puede no reflejar exactamente la verdadera inteligencia de la persona (**error**).
Así como hay diferentes tipos de **propiedades** que los objetos pueden tener (por ejemplo: altura, peso, color, inteligencia), también hay diferentes tipos de **escalas** con las que se pueden medir estas propiedades. Cada uno de estos diferentes tipos de escalas puede proporcionarle diferentes tipos de información, y solo puede realizar ciertos tipos de operaciones matemáticas con cada tipo de escala.
Los cuatro tipos principales de escalas son:
* **Escala nominal** - Esta escala implica asignar nombres a objetos. Por ejemplo, en una encuesta a menudo identificamos a las personas como "hombres" o "mujeres". Esto sería considerado una escala nominal. La única operación matemática disponible para esta escala es la evaluación de la igualdad. En otras palabras, con escalas nominales, solo puede determinar si dos objetos son iguales o no lo son.
* **Escala ordinal** - Esta escala implica colocar objetos en un orden particular. Por ejemplo, en una encuesta a menudo tiene preguntas con las siguientes opciones de respuesta: "No estar para nada de acuerdo", "No estar de acuerdo", "Ni de acuerdo ni en desacuerdo", "De acuerdo" y "Estar totalmente de acuerdo". Esta sería una escala ordinal. Hay dos operaciones matemáticas posibles con escalas ordinales: igualdad y más/menos. Por ejemplo, con esta escala puede determinar si dos objetos dan respuestas iguales (por ejemplo, dos personas que responden "de acuerdo" a una pregunta en una encuesta) o si la respuesta de una persona es "mayor" que la de otra. Por ejemplo, si la Persona A responde "de acuerdo" y la Persona B responde "estar totalmente de acuerdo", puede estar seguro de que la Persona B acepta más el elemento que la Persona A. Sin embargo, no puede determinar la "distancia" entre los ítems. En otras palabras, tomando nuestro ejemplo, no sabe cuánto más concuerda la Persona B que la Persona A.
* **Escala de intervalo**: Esta escala implica colocar objetos en posiciones que tienen un orden significativo y distancia con respecto a otros objetos. Por ejemplo, el clima en dos días puede tener dos temperaturas diferentes. Digamos que el Día 1 tiene una temperatura de 10 grados centígrados y el Día 2 tiene una temperatura de 20 grados centígrados. Este es un ejemplo de una escala de intervalo. Con esta escala, podemos usar tres operaciones matemáticas diferentes: podemos determinar si dos objetos son iguales, si uno es mayor que otro, y también la distancia relativa entre ellos. En nuestro ejemplo, claramente el Día 1 y el Día 2 tienen dos temperaturas diferentes, y el Día 2 es más caluroso que el Día 1. Pero incluso más que eso, podemos decir que el Día 2 es exactamente 10 grados centígrados más caluroso que el Día 1. A diferencia de una escala ordinal, la distancia entre dos puntos en la escala es significativa. Sin embargo, no podemos determinar relaciones entre dos puntos en la escala. En nuestro ejemplo, no podemos decir que el Día 2 fue el doble de caliente que el Día 1. Esto se debe a que 0 grados se colocan arbitrariamente. Cuando hace 0 grados afuera, hace frío, pero todavía hay una temperatura presente.
* **Escala de cociente** - Esta escala es como una escala de intervalo, excepto que también tiene un punto "0" significativo. Podemos aplicar cuatro operaciones matemáticas diferentes a esta escala: las tres de una escala de intervalo además de la multiplicación/división. Por ejemplo, imagine que la Persona A mide 100 cm de altura y la Persona B mide 150 cm de altura. Claramente podemos determinar que la Persona A no es la misma altura que la Persona B, la Persona A es más baja que la Persona B y la Persona A es 50 cm más baja que la Persona B. Pero incluso más que eso, porque 0 cm es significativo, podemos decir que Persona B es 50% más alto que la Persona A. Podemos crear una proporción entre sus alturas. A diferencia de la temperatura, podemos decir con certeza dónde está 0 cm. Si algo mide 0 cm, ¡entonces no está!
La siguiente tabla ofrece un resumen de qué tipo de información es posible con cada escala.
```{r plot-scales, eval=TRUE, echo=FALSE}
include_graphics("Images/scales.png")
```
La mayoría de las preguntas de la MDS están en una escala ordinal de 5 puntos (por ejemplo, 1 = Ninguna, 2 = Algunas, 3 = Moderada, 4 = Mucho, 5 = Completa). Para crear un puntaje que podamos usar y confiar, lo que queremos hacer es **tomar nuestros datos ordinales y mapearlos en una escala de intervalos** de discapacidad. En otras palabras, al usar la regla de abajo como referencia, queremos pasar de la parte superior de la regla a la parte inferior.
```{r plot-ruler, eval=TRUE, echo=FALSE}
include_graphics("Images/ruler.png")
```
¿Por qué simplemente agregar datos ordinales no es lo suficientemente bueno? Imagine que es el CEO de una empresa que vende jugo de naranja. Le pregunta a sus empleados, ¿cuánto jugo de naranja podremos producir este trimestre? El Empleado A responde que la compañía ha producido **5000 naranjas** mientras que el Empleado B responde que la compañía ha producido **1500kg de naranjas**. ¿Quién le dio más información sobre la cantidad de jugo de naranja que podrá producir?
El Empleado B le dio información sobre una escala de intervalo (peso), y el Empleado A le dio información sobre una escala ordinal (conteo). El Empleado B le dio más información; Con su respuesta, usted sabe exactamente cuánto jugo de naranja puede vender. El Empleado A le dijo cuántas naranjas tiene, pero no tiene idea de cuán grandes o pequeñas son.
```{r plot-oranges, eval=TRUE, echo=FALSE}
include_graphics("Images/oranges.png")
```
Este escenario es similar a nuestro cuestionario. Podríamos simplemente sumar todas las respuestas a todas las preguntas que nos interesan para calcular una puntuación total. Sin embargo, esa puntuación total no nos dice mucho sobre el nivel general de discapacidad que una persona experimenta, porque no sabemos qué preguntas se identificaron como difíciles y las diferentes preguntas tienen diferentes niveles de dificultad.
Por ejemplo, imagine que una persona está respondiendo preguntas de la Encuesta Modelo sobre la Discapacidad. Esta persona respondió "3 = Algunos problemas" a las dos preguntas: "¿Qué tan problemático ha sido para usted utilizar el servicio sanitario?" y "¿Qué tan problemático ha sido para usted dormir?". Uno puede imaginar que las dificultades para dormir son bastante comunes, y muchos de nosotros experimentamos problemas con el sueño sin que esto afecte nuestras vidas demasiado. Sin embargo, muchas menos personas tienen "algunos problemas" con el uso del inodoro, y uno puede imaginar que tener incluso un cierto nivel de dificultad para usar el inodoro puede causar problemas significativos en la vida de alguien. Por lo tanto, se puede ver que la respuesta de "3" a "dormir" no es equivalente a la respuesta de "3" a "utilizar el servicio sanitario".
Así que, en esencia, estamos tratando de pasar de contar las respuestas a las preguntas sobre discapacidad a medir realmente los niveles de discapacidad en una escala de intervalo. Lo haremos usando **Análisis Rasch**.
# ¿Cómo se aplica una escala de intervalo para medir la discapacidad?
Antes de comenzar la discusión de la técnica del Análisis de Rasch, es importante enfatizar nuevamente la comprensión de la OMS sobre la discapacidad. Estamos midiendo la discapacidad en una **escala de intervalo**. Esta escala varía de 0 (sin discapacidad) a 100 (discapacidad extrema), y cada persona de la población se encuentra en algún lugar de la escala.
Esto es muy diferente de la forma tradicional de pensar sobre la discapacidad. A menudo, cuando las personas escuchan la palabra "discapacidad", piensan en diferentes "tipos de discapacidades", y las personas que más rápidamente vienen a la mente son, por ejemplo, las personas ciegas, las personas sordas o las que usan sillas de ruedas. Para la OMS, la palabra "discapacidad" no se refiere a los atributos de grupos específicos y limitados de personas que tienen discapacidades particulares. Para la OMS, "discapacidad" se refiere a una experiencia universal, no un atributo de una persona, que es el resultado de una multitud de factores, como una condición de salud subyacente o la accesibilidad de un entorno.
Por ejemplo, piense en una persona que tiene un impedimento de la vista debido a un glaucoma y otra persona que tiene un impedimento de movilidad debido a una lesión de la médula espinal. Ambas personas pueden tener dificultades para usar el sistema de transporte. La persona con una discapacidad visual puede tener dificultades para usar el transporte porque los nombres de las paradas en el autobús no se anuncian por el altavoz, por lo que la persona no puede saber cuándo ha llegado a su destino. La persona con problemas de movilidad puede tener dificultades para usar el sistema de transporte porque los autobuses no tienen rampas que le permitan bajar independientemente con su silla de ruedas. A pesar del hecho de que estas dos personas tienen diferentes tipos de impedimentos y se enfrentan con diferentes tipos de barreras, el _nivel de discapacidad_ que experimentan es bastante similar en este dominio particular del transporte.
La salida del Análisis Rasch nos dará el puntaje de discapacidad para cada persona en la muestra. Luego podemos trazar estos puntajes en un histograma para obtener una imagen general de la distribución de la discapacidad en una población. A continuación se muestra un ejemplo de dicha distribución. Puedes pensar en el eje horizontal como una regla. Cada persona se sienta en algún lugar de esta regla, y las alturas de los barrotes indican cuántas personas se encuentran en esa posición particular en la regla.
```{r plot-distributionruler, eval=TRUE, echo=FALSE}
include_graphics("Images/distributionruler.png")
```
# ¿Por qué debemos usar el Análisis de Rasch?
## Propiedades importantes
La razón principal por la que usamos Rasch Analysis ya se ha mencionado: nos permite tomar datos ordinales y mapearlos en una escala de intervalo. Sin embargo, hay otras propiedades importantes del Modelo Rasch que lo convierten en un método particularmente útil para nuestros propósitos:
* No se hacen suposiciones sobre la distribución de las capacidades de personas.
* Las dificultades de dos ítems pueden compararse independientemente de las capacidades de las personas
* Las capacidades de dos personas se pueden comparar independientemente de las dificultades de los ítems
* La diferencia entre las capacidades de las personas y las dificultades de los ítems es una _estadística suficiente_ (consulte un texto estadístico para obtener más información sobre estadísticas suficientes)
## Metas
En última instancia, tenemos tres objetivos principales al realizar el Análisis Rasch:
1. Obtener estimaciones de las capacidades de la personas
2. Conocer la dificultad de los ítems en la escala.
3. Crear y **validar** una herramienta de medición **confiable** de escala de intervalos
En otras palabras, la Meta 1 nos da los puntajes de discapacidad que estamos buscando. La Meta 2 nos dice qué "difíciles" los ítems son, es decir, qué tan indicativos son los diferentes niveles de discapacidad (leve, moderada, grave).
La Meta 3 tiene que ver con las propiedades psicométricas del instrumento de encuesta que estamos utilizando. Con el Análisis Rasch, además de calcular la escala de intervalo, estamos realizando simultáneamente un análisis de la validez y confiabilidad de la escala. Si nuestros datos se ajustan a la propiedad del modelo, podemos estar seguros de que los puntajes que obtenemos para las personas y para los artículos son válidos (es decir, están midiendo lo que pretendemos medir) y confiables (es decir, el instrumento de la encuesta daría resultados consistentes si la encuesta fue repetida).
## Salida
Como ya se mencionó anteriormente, uno de nuestros objetivos es obtener las estimaciones de las capacidades de las personas. Esto significa que una salida del Análisis de Rasch será un continuo de rasgo latente (se muestra a continuación) ...
```{r plot-continuum, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum.png")
```
... donde puede localizar personas específicas ...
```{r plot-continuum-person, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum_person.png")
```
...y también los ítems!
```{r plot-continuum-personitem, eval=TRUE, echo=FALSE}
include_graphics("Images/continuum_personitem.png")
```
"Continuo del rasgo latente" es otra frase para describir la escala. "Rasgo latente" se refiere a una característica subyacente de la población que el instrumento de la encuesta está midiendo (en nuestro caso, discapacidad). "Continuo" es simplemente otra palabra para "escala", enfatizando que las personas pueden ubicarse en cualquier punto entre los puntos finales (0 y 100) de la escala.
La figura anterior ilustra un ejemplo que analiza la fuerza de las personas y la dificultad de cada elemento (preguntas Q1 a Q10) en relación con la fuerza. La persona más fuerte está en el lado izquierdo del continuo, mientras que la persona más débil está en el lado derecho del continuo. Podemos ver que los artículos Q9 y Q10 son los más fáciles; están ubicados en el mismo extremo del continuo que la persona más débil. La probabilidad de que las personas más fuertes en el extremo izquierdo del continuo obtengan las preguntas "correctas" es muy alta. Las preguntas Q1 y Q2 son las más difíciles; solo las personas más fuertes, ubicadas en el mismo extremo del continuo, tienen una probabilidad razonable de que estas preguntas sean "correctas".
# ¿Qué es el Análisis de Rasch?
El Análisis de Rasch fue nombrado por el matemático danés Georg Rasch (1901-1980). La idea fundamental del Análisis de Rasch fue resumida por Rasch de la siguiente manera:
> ... una persona que tenga una capacidad mayor que otra persona debería tener la mayor probabilidad de resolver cualquier elemento del tipo en cuestión y, de manera similar, un elemento es más difícil que otro significa que para cualquier persona la probabilidad de resolver el segundo elemento es el mayor.
Esta cita de Rasch se refiere a dos situaciones:
1. Si tenemos dos personas, la Persona A y la Persona B, y la Persona A tiene más discapacidad que la Persona B, entonces la Persona A tiene una mayor probabilidad de calificar cualquier artículo dado en la encuesta, por ejemplo, "caminar 100 m", como más difícil que la persona B.
2. Si tenemos dos ítems, el Ítem A y el Ítem B, y el Ítem A es más difícil que el Ítem B, entonces cualquier persona tendrá una mayor probabilidad de calificar el Ítem A como más difícil que el Ítem B.
Rasch es uno de los modelos más simples en **Teoría de la respuesta del artículo (IRT, por sus siglas en inglés)**. IRT es un enfoque de medición **probabilístico**: la probabilidad de una respuesta "correcta" a un elemento (es decir, una pregunta) es una función (es decir, una relación) de los parámetros (es decir, las características) de la persona y el elemento.
Bajo el Modelo de Rasch, la probabilidad de cierta respuesta a un elemento de medición está asociada con la capacidad del encuestado ($\beta_n$) y la dificultad del ítem ($\delta_i$). Usando nuestro ejemplo anterior de una prueba de matemáticas, la capacidad de la persona $\beta_n$ sería la inteligencia matemática de la persona, y la dificultad del ítem $\delta_i$ sería la dificultad de cualquier pregunta dada en la prueba.
Hay dos versiones diferentes del modelo: la versión dicotómica (todas las preguntas tienen dos opciones de respuesta, por ejemplo 0 y 1) y la versión politómica (las preguntas tienen más de 2 opciones de respuesta). El modelo politómico, en el que estamos más interesados porque en el MDS la mayoría de las preguntas utiliza una escala de 5 puntos que va desde "1 = sin problemas" a "5 = problemas extremos", es simplemente una extensión de la versión dicotómica. A continuación damos una descripción básica de los modelos.
## El Modelo Rasch - Dicotómico
A continuación se muestra la principal ecuación para el Modelo de Rasch dicotómico (dos opciones de respuesta):
$$P(X_{ni}=1) = \frac{e^{\beta_n-\delta_i}}{1+e^{\beta_n-\delta_i}}$$
en la que:
* $i$ - contador de ítems
* $n$ - contador de personas
* $X_{ni}$ - variable aleatoria del puntaje de la persona $n$ en ítem $i$
* $\beta_n$ - la ubicación de la persona $n$ en el continuo latente
* $\delta_i$ - la dificultad de ítem $i$ en el continuo latente
En palabras más simples, esto significa: la **probabilidad** de que esa persona $n$ responde a la pregunta $i$ correctamente es una **proporción** basada en la diferencia entre la capacidad de esa persona ($\beta_n$) y la dificultad de esa artículo ($\delta_i$).
Esto se puede ver en la siguiente figura. El eje vertical es la probabilidad de que la persona responda a una pregunta correctamente ($P(X_{ni}=1)$), con un rango de 0 a 1. El eje horizontal es la diferencia entre la capacidad de una persona y la dificultad del ítem ($\beta_n-\delta_i$). Digamos que esta pregunta tiene dos opciones: 0 y 1, y una respuesta "correcta" al elemento es la opción de respuesta de 1. Cuando la capacidad de la persona y la dificultad del elemento son iguales ($\beta_n-\ delta_i=0$ o $\beta_n=\delta_i$), entonces la probabilidad de que la persona responda correctamente a la pregunta es del 50%. Si la capacidad de la persona es mayor que la dificultad del elemento ($\beta_n>\delta_i$), entonces la probabilidad de que la persona responda correctamente a la pregunta es superior al 50%. Si la capacidad de la persona es menor que la dificultad del ítem ($\beta_n<\delta_i$), entonces la probabilidad de que la persona responda correctamente a la pregunta es menor al 50%.
``` {r rasch-setup, echo=FALSE, eval=TRUE, out.width = NULL}
x <- seq(-5,5,0.01)
y <- exp(x)/(1+exp(x))
df <- tibble(x,y)
ggplot(df,aes(x=x,y=y)) +
geom_point() +
labs(x="Diferencia entre la capacidad de una persona y la dificultad del ítem", y="Probabilidad de que la persona responda \na una pregunta correctamente")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
```
## El Modelo Rasch - Politómico
El modelo de Rasch politómico (más de 2 opciones de respuesta) es una extensión de la versión dicotómica. También es conocido como el **Modelo de crédito parcial**. La principal ecuación para este modelo es:
$$P(X_{ni}=x) = \frac{e^{\sum^x_{k=0}(\beta_n-\tau_{ki})}}{\sum^{m_i}_{j=0}e^{\sum^j_{k=0}(\beta_n-\tau_{ki})}}$$
en la que:
* $i$ - contador de ítems
* $n$ - contador de personas
* $X_{ni}$ - variable aleatoria de el puntaje de la persona $n$ en ítem $i$
* $\beta_n$ - la ubicación de la persona $n$ en el continuo latente
* $\tau_{ki}$ - $k^{th}$ el umbral de ítem $i$ en el continuo latente
* $m_i$ - el puntaje máximo del ítem $i$
En palabras más simples, la **probabilidad** de que esa persona $n$ dé la respuesta $x$ a la pregunta $i$ es una **proporción** basada en la diferencia entre la capacidad de esa persona ($\beta_n$) y la dificultad de cada opción de respuesta ($\tau_{ki}$) para ese ítem.
Esto se puede ver en la siguiente figura, que es similar a la figura para el modelo dicotómico. El eje vertical es la probabilidad condicional de que la persona logre elegir una opción de respuesta particular o superior ($P(X_{ni}>x)$), que va de 0 a 1. El eje horizontal es la diferencia entre la capacidad de una persona y la dificultad del ítem. La diferencia clave entre esta figura y la figura para el modelo dicotómico es que ahora tenemos una curva de probabilidad para cada umbral.
Un **umbral** es el punto entre dos opciones de respuesta adyacentes donde una persona tiene un 50% de probabilidad de dar una opción de respuesta u otra. La siguiente figura muestra el caso de cuatro opciones de respuesta, lo que significa que esta pregunta tiene tres umbrales (el 50% del punto entre las opciones de respuesta 1 y 2, el mismo punto entre las opciones 2 y 3, y el mismo punto entre las opciones 3 y 4).
En la siguiente figura, puede ver que la probabilidad de pasar el primer umbral (curva roja), es decir, obtener una puntuación de 2, es siempre mayor que la probabilidad de pasar el segundo (verde) o el tercer (azul) umbral. Esto muestra una propiedad clave del Modelo de Rasch politómico: los umbrales están **ordenados**.
``` {r rasch-setup-poly, echo=FALSE, eval=TRUE, out.width = NULL}
x <- seq(-5,5,0.01)
tao <- c(-2.5,0,2.5)
y0 <- exp(x-tao[1])/(1+exp(x-tao[1]))
y1 <- exp(x-tao[2])/(1+exp(x-tao[2]))
y2 <- exp(x-tao[3])/(1+exp(x-tao[3]))
df <- tibble(x,y0,y1,y2)
df.long <- df %>%
pivot_longer(!x, names_to = "Threshold", values_to = "y")
ggplot(df.long,aes(x=x,y=y,color=Threshold)) +
geom_point()+
scale_color_discrete(labels=c("First","Second","Third")) +
labs(x="Diferencia entre la capacidad de una persona y la dificultad del ítem",
y="Probabilidad condicional de que la persona logre \nelegir una opción de respuesta particular o superior")+
geom_hline(yintercept=1, color="red", linetype=2) +
geom_hline(yintercept=0, linetype=2) +
geom_vline(xintercept=0)
```
# ¿Cómo se hace el Análisis de Rasch?
## El resumen del método
Todo lo que hemos descrito hasta ahora es un trasfondo de la lógica del Análisis de Rasch. Sin embargo, en este punto aún no hemos descrito cómo se lo hace realmente.
En general, la técnica básica es **ajustar nuestros datos al Modelo Rasch**, tomando nota de lo bien que se ajusta a las **suposiciones del Modelo Rasch**. Esto difiere de otros tipos de modelado en los que se adapta un modelo a sus datos. El modelo de Rasch se ve como el "ideal", y queremos ajustar nuestros datos de manera que puedan ajustarse a este ideal. Si nuestros datos se ajustan razonablemente a este ideal, podemos estar seguros de que tenemos una escala de intervalo **válida** y **confiable**.
El análisis de Rasch es un **proceso iterativo**, lo que significa que debe realizarse varias veces para alcanzar un resultado. El proceso se muestra en la siguiente figura.
``` {r iteration, echo=FALSE, eval=TRUE}
include_graphics("Images/iteration_ES.png")
```
La siguiente pregunta, naturalmente, es: ¿cuáles son los suposiciones de Rasch que estamos probando?
## Las suposiciones de Rasch
Los suposiciones del Modelo Rasch son los siguientes. Cada suposición será discutido en detalle en las siguientes secciones:
1. Independencia de ítems
2. Unidimensionalidad
3. Ordenamiento estocástico
4. Invariación de grupo
5. Ajuste al modelo
También analizaremos a continuación cómo ajustar los datos para que se ajusten mejor a cada supuesto. Es posible que estas técnicas no tengan mucho sentido ahora, pero se aclararán una vez que analicemos el ejemplo.
### Independencia de ítems
Independencia de los ítems se refiere a la incorrelación entre los ítems. En otras palabras, queremos que las respuestas a un ítem NO se relacionen fuertemente con las respuestas de otro ítem. La correlación ocurre cuando los ítems están vinculados por atributos, contenido, estructuras o temas comunes. Por ejemplo, en el MDS dos ítems que a menudo están relacionados son "¿Qué tan problemático ha sido para usted sentir tristeza, desánimo o depresión?" y "¿Qué tan problemático ha sido para usted sentir preocupación, nerviosismo o ansiedad?"
Para solucionar problemas con alta correlación, a menudo agregamos ítems dependientes en un "súper ítem" o "testlet". Por ejemplo, si tenemos dos ítems, cada uno con 5 opciones de respuesta, que están altamente correlacionados, podríamos combinarlos en un testlet sumando las respuestas para cada persona. Este testlet ahora tendría 9 opciones de respuesta.
### Unidimensionalidad
La unidimensionalidad se refiere a la situación en la que todos los ítems miden la misma construcción única subyacente. En el caso de la MDS, queremos que todos los ítems midan la misma construcción subyacente de "discapacidad". Una puntuación total solo es significativa con una escala unidimensional.
Toma otro ejemplo en la situación educativo: imagine una prueba de matemáticas. Todos los ítems de esta prueba miden la misma construcción subyacente, es decir, la capacidad de la persona en matemáticas. Si una prueba de matemáticas también contuviera preguntas de literatura en inglés, la escala creada con todos los ítems de esta prueba ya no sería unidimensional porque la prueba se compone de dos conjuntos de ítems totalmente separados.
Si notamos problemas con la dimensionalidad de nuestros datos, podemos corregirlo dividiendo los ítems en múltiples escalas. En nuestro ejemplo educativo anterior, esto significaría crear una escala separada para las preguntas de matemáticas en la prueba y una escala separada para las preguntas de inglés.
### Ordenamiento estocástico
El ordenamiento estocástico se refiere a los umbrales (es decir, los límites entre las opciones de respuesta) que están en el orden correcto. Esperamos que la probabilidad de que una persona cruce el primer umbral sea mayor que la probabilidad de que pase el segundo, y de igual manera la probabilidad de cruzar el segundo umbral debe ser mayor que la probabilidad de cruzar el tercero, etc. Como analogía, piense en un salto de altura: si alguien puede saltar más de 1.5 m, entonces necesariamente ya saltó más de 1 m. El ordenamiento estocástico solo es relevante para los artículos con más de 2 opciones de respuesta (caso politómico).
```{r plot-highjump, eval=TRUE, echo=FALSE}
include_graphics("Images/highjump.jpg")
```
Si tenemos problemas con el ordenamiento estocástico, podemos recodificar las opciones de respuesta para crear menos umbrales entre los ítems que es más probable que estén en orden.
### Invariancia de grupo
La invariancia de grupo se refiere a ítems que se comportan de manera similar para personas con diferentes características. Por ejemplo, queremos que hombres y mujeres muestren patrones similares de respuestas para un ítem. Si los elementos muestran un comportamiento diferente para diferentes grupos, esto se conoce como "funcionamiento diferencial de ítems (DIF, por sus siglas en inglés)".
Para la MDS, debido a que esperamos que los hombres y las mujeres experimenten diferentes niveles de discapacidad, no estamos demasiado preocupados por la invarianza del grupo. Esto es lo mismo para personas de diferentes edades, ya que a medida que envejecemos, mayor es la probabilidad de experimentar una discapacidad en la vida diaria.
Si queremos corregir el DIF, podemos dividir los elementos en subgrupos. Por ejemplo, en lugar de tener una pregunta Q1 para toda la muestra, podemos dividirla en dos preguntas Q1_Men y Q1_Women.
### Ajuste al modelo
Además de todas las suposiciones anteriores, también nos preocupamos por el ajuste al modelo. El ajuste de los ítems, las personas y el modelo en general se miden con diversas estadísticas de ajuste.
Nosotros determinamos:
* ¿Los **ítems** se ajustan al modelo? -> examinar el ajuste de ítems
* ¿Las **personas** se ajustan al modelo? -> examinar el ajuste de personas
* ¿Cómo es el modelo **en general**? -> examinar los puntajes de confiabilidad, como el índice de separación de personas (PSI, por sus siglas en inglés)
Si los ítems o las personas se muestran mal ajustados al modelo después de realizar todos los demás ajustes que podríamos hacer, todo lo que queda por hacer es eliminar ítems o personas de la escala. Esto se consideraría un último recurso, ya que significa que la escala que termina creando no examina todos los ítems o personas que originalmente se propuso medir.
## ¿Por qué tengo que ejecutar el modelo varias veces?
Es muy raro que el primer modelo que ejecute dé resultados perfectos donde todo se ajusta. Si su objetivo es simplemente evaluar la validez y confiabilidad de su cuestionario con los datos sin procesar, entonces podría ejecutar el modelo una vez y analizar esos resultados. Sin embargo, si su objetivo es obtener una puntuación válida y confiable, como ocurre en el caso del MDS, lo más frecuente es que sea necesario ejecutar el modelo varias veces, haciendo ajustes a los datos cada vez. Estamos tratando de encontrar una manera de ajustar los datos al "ideal" de Rasch, en otras palabras, para crear una puntuación que se adhiera a estas suposiciones básicas incorporadas en el modelo de Rasch. El hecho de que deba ejecutar el modelo varias veces no significa necesariamente que haya algún problema con su cuestionario. El proceso de Análisis de Rasch simplemente le indica la mejor manera de utilizar el instrumento de encuesta que tiene para crear la puntuación más confiable.
## ¿Dónde empiezo? {#repair}
La siguiente figura muestra la ruta de reparación para el modelo de Rasch. En general, puede ver que todas estas suposiciones pueden afectar el desempeño de otras suposiciones. Sin embargo, se puede determinar una guía general sobre qué orden usar cuando se ajustan los datos.
```{r plot-repair, eval=TRUE, echo=FALSE}
include_graphics("Images/repair.png")
```
La dependencia local (o independencia del ítem) afecta la unidimensionalidad, el ordenamiento de umbrales (o el ordenamiento estocástico) y el ajuste al modelo, por lo que es bueno comenzar por cuidar en primer lugar la independencia del ítem La unidimensionalidad afecta el ordenamiento de umbrales y el ajuste al modelo, por lo que es una buena suposición cuidar en segundo lugar. El ordenamiento de umbrales afecta el ajuste al modelo, por lo que puede ser atendido en tercer lugar. Finalmente, la invariancia de grupo solo afecta el ajuste al modelo, por lo que puede ser atendido en último lugar.
## ¿Cómo puedo saber cuándo he terminado?
Determinar cuándo puede dejar de ejecutar iteraciones del Modelo Rasch no es totalmente sencillo. Aprenderemos reglas generales, pero se necesita práctica para tener una idea de lo que es "suficientemente bueno". El resto de esta guía le mostrará lo que debe examinar para determinar cuándo sus datos se ajustan al modelo lo suficientemente bien.
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c1_background_ES.Rmd
|
---
title: "2 - Getting started with WHO package for Rasch Analysis"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{2 - Getting started with WHO package for Rasch Analysis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Introduction
WHO performs the Rasch Analysis for the Model Disability Survey using the software `R`. `R` is an open source, statistical programming software. How to program in `R` is beyond the scope of this guide. However the codes we will discuss as follows have been written in such a way to require minimal programming knowledge, and this guide tries to make the instructions for how to use them as simple as possible.
To learn about `R`, please see the references provided at the end of this guide.
To use the package provided by WHO, `R` must be installed from the [Comprehensive R Archive Network (CRAN)](https://cran.r-project.org). We also recommend installing [RStudio](https://posit.co/download/rstudio-desktop/), a very popular integrated development environment (IDE), for `R`. One can think of the relationship between `R` and `RStudio` like a car: `R` is the engine of the car, while `RStudio` is the dashboard and controls. `RStudio` cannot be run without `R`, but it makes `R` easier to use. Both are free to install and use indefinitely.
# What is a package and how do I install one?
A "package" is a collection of `R` functions, data and code with a specific purpose and in a well-defined format. There are thousands of packages for `R` that have been written by `R` users. People write packages in order to share codes they have written that make specific tasks easier. WHO has written a package in order to make analysis of the data from the MDS easier. The package written by WHO is called `whomds`. To install the package, run the following code in the console:
```{r install-cran}
install.packages("whomds")
```
# Using `whomds`
Once `whomds` is installed, it can be opened with the following code:
```{r open-whomds}
library(whomds)
```
`whomds` contains three kinds of functions:
* `table_*()` functions - produce different fit-for-purpose tables
* `fig_*()` functions - produce different fit-for-purpose figures
* `rasch_*()` functions - used when performing Rasch Analysis
In this section we will focus on the `rasch_*()` functions.
There are two sets of `rasch_*()` functions in the `whomds` package: one set for adults, and one set for children. The reason different functions are needed for each group is that the type of Rasch Analysis performed for each group is different. The Rasch Analysis performed for adults is straightforward; the whole adult population can be considered in one group. The Rasch Analysis for children requires a more complicated analysis, because children at different ages are very different, and they can perform vastly different types of activities. First we will describe the analysis of adults, and then describe the analysis of children.
## Package dependencies
The package `whomds` depends on several other packages to run properly. When `whomds` is installed, all of the other packages it uses will also be installed. Be sure that these other packages are installed correctly by investigating any errors that arise during installation.
The additional packages are:
* `colorspace`
* `dplyr`
* `eRm`
* `ggraph`
* `ggplot2`
* `GPArotation`
* `grDevices`
* `igraph`
* `nFactors`
* `plyr`
* `polycor`
* `purrr`
* `RColorBrewer`
* `readr`
* `rlang`
* `scales`
* `srvyr`
* `stringr`
* `TAM`
* `tibble`
* `tidygraph`
* `tidyr`
* `WrightMap`
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c2_getting_started_EN.Rmd
|
---
title: "2 - Empezar con el paquete de OMS para Análisis Rasch"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{2 - Empezar con el paquete de OMS para Análisis Rasch}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Introducción
La OMS realiza el Análisis de Rasch para la Encuesta Modelo sobre la Discapacidad utilizando el software `R`. `R` es un software de programación estadística de código abierto. Cómo programar en `R` está fuera del alcance de esta guía. Sin embargo, los códigos que analizaremos a continuación se han escrito de tal manera que requieren un conocimiento mínimo de programación, y esta guía trata de hacer que las instrucciones sobre cómo usarlas sean lo más simples posible.
Para obtener información sobre `R`, consulte las referencias proporcionadas al final de esta guía.
Para usar el paquete provisto por la OMS, `R` debe instalarse en el [Comprehensive R Archive Network (CRAN)](https://cran.r-project.org). También recomendamos instalar [RStudio](https://posit.co/download/rstudio-desktop/), un _integrated development environment (IDE)_ muy popular, para `R`. Se puede pensar en la relación entre `R` y` RStudio` como un automóvil: `R` es el motor del automóvil, mientras que` RStudio` es el tablero y los controles. `RStudio` no se puede ejecutar sin `R`, pero hace que `R` sea más fácil de usar. Ambos son gratis de instalar y usar indefinidamente.
# ¿Qué es un paquete y cómo instalo uno?
Un "paquete" es una colección de funciones, datos y código `R` con un propósito específico y en un formato bien definido. Hay miles de paquetes para `R` que han sido escritos por usuarios de `R`. Las personas escriben paquetes para compartir los códigos que han escrito que facilitan las tareas específicas. La OMS ha escrito un paquete para facilitar el análisis de los datos del MDS. El paquete escrito por la OMS se llama `whomds`. Se puede instalar `whomds` ejecutando el siguiente código en la consola:
```{r install-cran}
install.packages("whomds")
```
# Utilizar `whomds`
Una vez que se instala `whomds`, se puede abrir con el siguiente código:
```{r open-whomds}
library(whomds)
```
`whomds` contiene tres tipos de funciones:
* Funciones `table_*()` - producen diferentes tablas de estadísticas descriptivas
* Funciones `fig_*()` - producen diferentes figuras
* Funciones `rasch_*()` - utilizadas al realizar el Análisis Rasch
En esta sección nos centraremos en las funciones `rasch_*()`.
Hay dos conjuntos de funciones `rasch_*()` en el paquete `whomds`: un conjunto para adultos y otro para niños. La razón por la que se necesitan diferentes funciones para cada grupo es que el tipo de Análisis de Rasch realizado para cada grupo es diferente. El Análisis de Rasch realizado para adultos es sencillo; Toda la población adulta puede ser considerada en un grupo. El Análisis de Rasch para niños requiere un análisis más complicado, porque los niños de diferentes edades son muy diferentes y pueden realizar diferentes tipos de actividades. Primero describiremos el análisis de los adultos, y luego describiremos el análisis de los niños.
## Dependencias de paquetes
El paquete `whomds` depende de varios otros paquetes para funcionar correctamente. Cuando se instale `whomds`, también se instalarán todos los demás paquetes que utiliza. Asegúrate de que estos otros paquetes se instalen correctamente investigando cualquier error que surja durante la instalación.
Los paquetes adicionales son:
* `colorspace`
* `dplyr`
* `eRm`
* `ggraph`
* `ggplot2`
* `GPArotation`
* `grDevices`
* `igraph`
* `nFactors`
* `plyr`
* `polycor`
* `purrr`
* `RColorBrewer`
* `readr`
* `rlang`
* `scales`
* `srvyr`
* `stringr`
* `TAM`
* `tibble`
* `tidygraph`
* `tidyr`
* `WrightMap`
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c2_getting_started_ES.Rmd
|
---
title: "3 - Rasch Analysis for MDS data from adults"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{3 - Rasch Analysis for MDS data from adults}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Structure
To perform Rasch Analysis for adults, only one function needs to be used: `rasch_mds()`. This is referred to as a "wrapper function." A wrapper function is a function that makes it easier to use other functions. In our case, `rasch_mds()` utilizes all the other `rasch_*()` functions to perform the analysis. These other `rasch_*()` functions used for adults are:
* `rasch_DIF()`
* `rasch_drop()`
* `rasch_factor()`
* `rasch_model()`
* `rasch_rawscore()`
* `rasch_recode()`
* `rasch_rescale()`
* `rasch_split()`
* `rasch_testlet()`
You only need to use the function `rasch_mds()`. But if you wanted to perform your analysis in a more customized way, you could work with the internal functions directly.
# Output
After each iteration of the Rasch Model, the codes above produce a variety of files that will tell you how well the data fit the assumptions of the model at this iteration. The most important files are the ones below. We will explain each in detail through our example.
* `LID_plot.pdf` - shows correlated items
* `LID_above_0.2.csv` - correlations between correlated items
* `parallel_analysis_scree.pdf` - scree plot
* `bifactor_analysis.pdf` - loadings of factors
* `PImap.pdf`- locations of persons and items, ordering of thresholds
* `item_fit.csv` - item fit
* `Targeting.csv` - reliability of model
# Arguments of `rasch_mds()`
In this section we will examine each argument of the function `rasch_mds()`. The help file for the function also describes the arguments. Help files for functions in `R` can be accessed by writing `?` before the function name, like so:
```{r rasch-mds-help}
?rasch_mds
```
Below is an example of a use of the function `rasch_mds()`:
```{r rasch-mds-example}
rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run"
)
```
The first argument is `df`. This argument is for the data. The data object should be individual survey data, with one row per individual. Here the data is stored in an object `df_adults`, which is a dataset included in the `whomds` package. To find out more about `df_adults` please look at its help file by running: `?df_adults`
The second argument is `vars_metric`, which is equal to a character vector of the column names for the items to use in Rasch Analysis. Here it is equal to `paste0("EF", 1:12)`, which is a character vector of length 12 of the column names `EF1`, `EF2`, ... `EF11`, and `EF12`.
The next argument is `vars_id`, which is the name of the column used to uniquely identify individuals. Here the ID column is called `HHID`.
The next argument is `vars_DIF`. It is equal to a character vector with the names of the columns that are used to analyze differential item functioning (DIF). DIF will be discussed in more detail in later sections. Here `vars_DIF` is equal to a character vector of length two containing the name of the columns `"sex"` and `"age_cat"`.
The next argument is `resp_opts`. This is a numeric vector with the possible response options for `vars_metric`. In this survey, the questions `EF1` to `EF12` have response options 1 to 5. So here `resp_opts` is equal to a numeric vector of length 5 with the values `1`, `2`, `3`, `4` and `5`.
The next argument is `max_NA`. This is a numeric value for the maximum number of missing values allowed for an individual to be still be considered in the analysis. Rasch Analysis can handle individuals having a few missing values, but too many will cause problems in the analysis. In general all individuals in the sample should have fewer than 15% missing values. Here `max_NA` is set to `2`, meaning individuals are allowed to have a maximum of two missing values out of the questions in `vars_metric` to still be included in the analysis.
The next argument is `print_results`, which is either `TRUE` or `FALSE`. When it is `TRUE`, files will be saved onto your computer with results from the Rasch iteration. When it is `FALSE`, files will not be saved.
The next argument is `path_parent`. This is a string with the path to the folder where the results of multiple models will be saved, assuming `print_results` is `TRUE`. The folder in `path_parent` will then contain separate folders with the names specified in `model_name` at each iteration. In the function call above, all results will be saved on the Desktop. Note that when writing paths for `R`, the slashes should all be: `/` (NOT `\`). Be sure to include a final `/` on the end of the path.
The next argument is `model_name`. This is equal to a string where you give a name of the model you are running. This name will be used as the name of the folder where all the output will be saved on your computer, if `print_results` is `TRUE`. The name you give should be short but informative. For example, you may call your first run "Start", as it is called here. If you create a testlet in your second run perhaps you can call it "Testlet1", etc. Choose whatever will be meaningful to you.
The next arguments are `testlet_strategy`, `recode_strategy`, `drop_vars` and `split_strategy`. These are arguments that control how the data is used in each iteration of the Rasch Model. Each will be discussed in more detail in later sections. Here they are all set to `NULL`, which means they are not used in the iteration of Rasch Analysis shown here.
The last argument is `comment`. This is equal to a string where you can write some free-text information about the current iteration so that when you are looking at the results later you can remember what you did and why you did it. It is better to be more detailed, because you will forget why you chose to run the model in this particular way. This comment will be saved in a file `Comment.txt`. Here the comment is just `"Initial run"`.
# Adjusting the data
Next, we will discuss the arguments that give instructions about how to adjust the data. These parts may not be entirely meaningful now, but will become more so after we go through an example.
## Making testlets
If you want to create testlets--that is, sum up items into super items in order to fix item dependence--then pass a strategy for making testlets to the argument `testlet_strategy`. `testlet_strategy` is a list with one element of the list per testlet that you want to create. Each element of the list must be a character vector of column names to use for the testlet. Optionally, you can name the elements of the list to give custom names to the new testlets. Otherwise, the new testlets will be the original column names separated by "_".
For example, imagine you wanted to make two testlets: one testlet from variables `EF4`, `EF6`, and `EF8` with a new name of `new`, and another testlet from `EF5` and `EF7`, without a new name specified. Then you would specify `testlet_strategy` as the following:
```{r rasch-mds-testlet}
rasch_mds(
...,
testlet_strategy = list(
new = c("EF4", "EF6", "EF8"),
c("EF5", "EF7")
)
)
```
## Recoding
If you want to recode response options--that is, change response options in order to create stochastic ordering--then pass a strategy for the recoding to the argument `recode_strategy`. `recode_strategy` takes the form of a named list, with one element of the list per recode strategy. The names of the list are the groups of column names to use for each recoding strategy, separated only by ",". Each element of the list is a numeric vector giving the new response options to map the variables to.
For example, if you wanted to collapse the last two response options of the variables `EF1` and `EF2`, and collapse the first two response options of `EF3`, then you would set `recode_strategy` as the following:
```{r rasch-mds-recode}
rasch_mds(
...,
recode_strategy = list(
"EF1,EF2" = c(0,1,2,3,3),
"EF3" = c(0,0,1,2,3)
)
)
```
## Dropping variables
If you want to drop any items from your analysis--perhaps in the event of extremely poor fit--then set `drop_vars` as a character vector of the column names to drop from the analysis.
For example, if the items `EF4` and `EF7` were extremely poorly fitting items, then they could be dropped from the analysis by setting `drop_vars` as the following:
```{r rasch-mds-drop}
rasch_mds(
...,
drop_vars = c("EF4", "EF7")
)
```
## Splitting
If you want to split items by subgroups--perhaps in the event of high differential item functioning (DIF)--then you give the instructions for your split strategy in the argument `split_strategy`.
Splitting items entails taking a single item and separating it into two or more items for different groups. For example, if we wanted to split an item `var` by sex, then we would create two items: `var_Male` and `var_Female`. `var_Male` would be equivalent to `var` for all respondents that are men, and `NA` for the respondents that are women. `var_Female` would be equivalent to `var` for all respondents that are women, and `NA` for the respondents that are men.
`split_strategy` takes the form of a named list. There is one element of the list per variable to split by. Each element of the list must be a character vector of column names to split. The names of the list are the variables to split each group of variables by.
For example, if we wanted to split the variables `EF1` and `EF2` by `sex`, and split `EF3` by age category `age_cat`, then we would set `split_strategy` to be the following:
```{r rasch-mds-split}
rasch_mds(
...,
split_strategy = list(
sex = c("EF1", "EF2"),
age_cat = c("EF3")
)
)
```
However, because we expect a certain amount of DIF when measuring disability--especially by sex and age--we rarely use this option. To not perform any splitting, leave `split_strategy` as its default value of `NULL.`
# Example
Below we will be creating a metric using the sample data `df_adults` using the environmental factors (EF) questions from the questionnaire. These are questions `EF1` to `EF12`.
## Start
We will start by trying to run the model without performing any adjustments on our data. To run this model, run a command that is similar to this:
```{r adult-start-example}
start <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run"
)
```
The code you run may not be exactly the same, because for instance the directory you use for `path_parent` will be specific to your machine, and you may choose a different `model_name` and `comment` for your model.
By running this command, in addition to printing results to your machine (because `print_results` is `TRUE`), you are also saving some output to an object in `R`'s global environment called `start`. This object is a list with three elements: one named `df`, one named `vars_metric`, and one named `df_results`. `df` contains the data with the transformed variables used to create the score and the rescaled scores. `vars_metric` is a character vector of the names of the `vars_metric` after transforming the variables. `df_results` is a data frame with one row and a column for each of the main statistics for assessing the assumptions of the Rasch Model. `df_results` from multiple models can be merged in order to create a data frame that allows you to quickly compare different models.
It is not necessary to save the output of `rasch_mds()` to an object in the global environment, but it makes it easier to manipulate the resulting output in order to determine what adjustments to make to your data in the next iteration.
After running this command, various files will be saved to the folder that you specified. Go to the `path_parent` folder, and you will see a new folder with the name you specified in `model_name`. Inside that folder, there will be many files. We will focus on the most important ones. Please read again Section \@ref(repair) to review how the different Rasch Model assumptions affect one another and to understand why we will check the important files in this particular order.
First we will check the local item dependence of the items. We can check this by looking at the files `LID_plot.pdf` and `LID_above_0.2.csv`. `LID_above_0.2.csv` gives the correlations of the residuals that are above 0.2, and `LID_plot.pdf` is a visualization of these correlations. From these files, we can see that the items `EF11` and `EF12` are correlated. The value of the correlation is approximately 0.47. These two items have to do with how facilitating or hindering work (`EF11`) and school (`EF12`) are. Conceptually, it makes sense that people's answers to these two questions are related. We will take care of this correlation at the next iteration of the model.
```{r adult-start-LID, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/LID_plot.png")
```
Next we will investigate the unidimensionality of the model by analyzing the file `parallel_analysis_scree.pdf`. This is what's known as a "scree plot." A scree plot shows the eigenvalues for our model, and indicates how many underlying dimensions we have in our questionnaire. With this scree plot, we hope to see a very sharp decline after the first eigenvalue on the left, and that the second eigenvalue falls below the green line of the "Parallel Analysis". This would mean that we have one underlying dimensions that is very strong in our data, and any further dimensions that are computed have very little influence on the model. In our graph, we do see a very sharp decline after the first eigenvalue, and the green line crosses the black line after the second factor. This is sufficient to confirm unidimensionality for the model.
```{r adult-start-scree, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/parallel_analysis_scree.png")
```
Another important file we can examine is the `PImap.pdf`. This is the "Person-Item Map", and it shows people and items on the same continuum. The horizontal axis on the bottom of the figure is this continuum, labeled as the "latent dimension". The top of the figure is labeled the "person parameter distribution". This is the distribution of people's scores on the continuum. It can show you if, for instance, you have more people on one end of the scale or another.
```{r adult-start-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/PImap.png")
```
The largest part of this figure shows where the thresholds for each item are located on the continuum. The thresholds are labeled with numbers: the first threshold is labeled "1", the second is labeled "2", and so on. The black dot is the average of the locations of all these thresholds. The stars on the right side of the figure indicate whether or not the thresholds are out of order. For instance, you can see for `EF1`, the thresholds are ordered 2, 4, 1, 3 which is clearly out of order. In fact, in this case, all of the items have thresholds out of order. This is likely something we will need to take care of later, but first we will take care of the item dependence.
Another important file we can analyze is `item_fit.csv`. This file gives the fit statistics for each item. Two fit statistics used here are "outfit" and "infit", given in the columns `i.outfitMSQ` and `i.infitMSQ`. They are both similar, but outfit is more sensitive to outliers. In general we hope that these figures are as close to 1 as possible. If they are below 1, then it indicates the item is overfitting. "Overfit" refers to the situation when items fit "too closely" to the model. If these statistics are greater than 1, then they indicate the items are underfitting. "Underfit" refers to the situation when items do not fit the model well. Underfitting is more serious than overfitting. We hope in general that items' infit and outfit are between 0.5 and 1.5. If they are less than 0.5, reliability measures for the model may be misleadingly high, but the scores can still be used. If they are between 1.5 and 2.0, this is a warning sign that the items may be causing problems and you could begin to consider adjusting the data to improve the fit. If they are greater than 2.0, the scores calculated may be significantly distorted and action should be taken to adjust the data to improve fit.
In this case, all of the items have infit and outfit statistics between 0.5 and 1.5, which is good.
To analyze overall model fit, we can open the file `Targeting.csv`. This file gives the mean and standard deviation of the person abilities and of the item difficulties. It also gives the "person separation index", or PSI, which is a measure of reliability for the model. We hope this value is as close to 1 as possible. It is generally acceptable if it is this figure is above 0.7, though we hope to get values as high as 0.8 or 0.9. For our model here, our PSI is 0.82, which is very good.
## Testlet1
With our next iteration of the model, we will try to address the high item dependence between items `EF11` and `EF12`. We will do this by creating a testlet between these two items. We do this by changing the argument `testlet_stratey` as shown below. We have given the new testlet the name `workschool`, but you could name it whatever you wished.
```{r adult-t1-example}
testlet1 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25)"
)
```
After running this model, we get an error:
```{r adult-t1-error, echo=FALSE, eval=TRUE, message=TRUE}
message("Error in tapply(1L:ncol(X01beta), mt_ind, function(xin) { :
arguments must have same length ")
```
This error is a bit strange looking. But sometimes errors like this will arise because of too many NAs in the data or if there are not enough people endorsing all possible response options. Let's look at the file `response_freq.csv` in order to see how the response options are distributed. We can see in this file that there are many endorsements for all response options for all questions except for our new testlet `workschool`, which only has 1 person with an answer of 6, and no one with the possible answers of 5, 7 or 8. Perhaps this is what is causing the problem.
### More on recoding
First let's discuss recoding in a bit more detail.
Each question with `n` response options will have `n-1` thresholds. The first threshold (labeled with a "1" in the person-item map) is the point between the first and second response option where a respondent is equally likely to choose either of these response options; the second threshold (labeled with a "2" in the person-item map) is the point between the second and third response option where a respondent is equally likely to choose either of these response options; and so on.
We want our thresholds in the person-item map to be in the right order: 1, 2, 3, 4 and so on. Disordered thresholds indicate a problem with our items. For example, if the thresholds are listed in the order 1, 2, 4, 3, then the data are telling us that someone is more likely to surpass the 4th threshold before the 3rd threshold, which does not make sense. We recode the response options in order create fewer thresholds so that it is easier for them to be in order.
The functions to perform Rasch Analysis shift our response options so that they start with 0. This is done because the functions for performing the analysis require it. For example, our survey has questions that have response options ranging from 1 to 5, but internally the function shifts these response options so they range from 0 to 4. Consequently, it becomes slightly more straightforward to interpret which response options need to be recoded directly from the labels of the thresholds. For example, if an item is disordered in the pattern 1, 2, 4, 3, this means that thresholds 4 and 3 are out of order. This also means that we can recode the transformed response options 4 and 3 in order to collapse these thresholds.
When we want to recode an item, we supply the function with instructions on what to map the response options to. For example, let's say an item `var` has disordered thresholds in the pattern 1, 2, 4, 3. We now want to collapse the 4th and the 3rd threshold so that the item becomes ordered. `var` has response options ranging from 0 to 4 (after being shifted from the original 1 to 5), so we want to combine the response options 3 and 4 for the item in order to collapse these two thresholds. We do this by telling the function to map the current response options of 0, 1, 2, 3, 4 to 0, 1, 2, 3, 3. This means all responses of "4" are now recoded to be "3". Now we will only have 4 different response options, which means we will have 3 different thresholds, which will now hopefully be in the proper order.
This will become clearer as we work through the example.
## Testlet1_Recode1
At the next iteration, we will try to recode the response options of our testlet so that the model is able to run.
We will run the command like below:
```{r adult-t1r1-example}
testlet1_recode1 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode1",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5"
)
```
The difference between the Testlet1 model and this model is that we have now added a recoding strategy. We will recode the response options of the testlet `workschool` to 0,1,2,3,4,5,5,5,5. This means all response options will stay the same, except the response options 5 through 8 are combined.
After we run the command, we see the model is able to be calculated as normal.
First we check `LID_plot.pdf` to see if we have been able to remove the item correlation. In this file, we see the message "No LID found", which means our testlet strategy was effective!
Next, we check the scree plot in the file `parallel_analysis_scree.pdf` to make sure our unidimensionality was maintained. Indeed, it looks very similar to the initial model, which is what we hope for.
Next we check the person-item map in `PImap.pdf`. We can see in this file all the items are still disordered, so this is likely the next thing we will have to take care of in the next iteration of the model.
```{r adult-t1r1-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode1/PImap.png")
```
We finally will check the item fit and the overall model fit in `item_fit.csv` and `Targeting.csv`, respectively. We can see these values are all still good--every item still has infit and outfit statistics between 0.5 and 1.5, and the PSI is still 0.82.
## Testlet1_Recode2
Next we will try recoding items in order to create ordered thresholds. We are most worried about having the single items (everything that is not a testlet) ordered.
There are various ways you can choose the recoding strategy. In general you want to do the minimum amount of recoding necessary to acheive ordered thresholds. We will try first to collapse the first two thresholds for all items that are not the testlet. We will see which items this works for, and try a new strategy at the next iteration for the items where it did not work.
```{r adult-t1r2-example}
testlet1_recode2 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode2",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,3)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,3"
)
```
We can see in the new person-item map that this strategy did not work for any of the items. So we will try a new strategy at the next iteration.
```{r adult-t1r2-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode2/PImap.png")
```
We can also check the other files to see if any other Rasch Model assumptions have now been violated with this recoding strategy. But because we are changing our strategy completely at the next iteration, it is not necessary to pay too much attention to the other files for this iteration.
## Testlet1_Recode3
From the person-item map for the Start model, we can see our items are disordered in a bit of a complicated way: many items have thresholds in order 2, 4, 1, 3 or in order 2, 3, 4, 1. Usually if an item has disordered thresholds in a fairly uncomplicated pattern (for example, 1, 2, 4, 3 or 2, 1, 3, 4) then then the recoding strategy is straightforward. For example, with disordering of 1, 2, 4, 3 it is clear that the respone options 3 and 4 should be collapsed. With disordering of 2, 1, 3, 4 then the response options of 1 and 2 should be collapsed.
In our case, the disordering is fairly complicated so the recoding strategy is less straightforward and will likely have to be more extreme. At this iteration, we will try collapsing two sets of response options: we will collapse 1 with 2 and 3 with 4, as shown below.
```{r adult-t1r3-example}
testlet1_recode3 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode3",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,2)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,2"
)
```
We can see with this recoding strategy that the thresholds are now ordered for most of the items! The only item it did not work for is `EF6`, which we will have to try a different strategy for at the next iteration.
```{r adult-t1r3-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode3/PImap.png")
```
We made progress on our threshold disordering, but we need to make sure that the other Rasch Model assumptions have not now been violated with this new strategy. We check `LID_plot.pdf` and see we still have achieved item independence. We also check the scree plot in `parallel_analysis_scree.pdf` to see if we still have unidimensionality. Finally, we also check `item_fit.csv` and `Targeting.csv` and see that the values are still acceptable in these files as well. So we will proceed with an altered recoding strategy in the next iteration.
## Testlet1_Recode4
We still have two items that are disordered: `EF6` and `workschool`. We do not generally worry about testlets being disordered because they are not items originally included in the questionnaire. We could recode `workschool` if its item fit was very poor, but in our model it maintains good item fit based on the infit and outfit statistics, so we will not recode it.
Therefore at this iteration we will just try to solve the disordering of `EF6`. We will try collapsing the middle three response options, as shown below.
```{r adult-t1r4-example}
testlet1_recode4 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode4",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF7,EF8,EF9,EF10" = c(0,1,1,2,2),
EF6 = c(0,1,1,1,2)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else except EF6 to 0,1,1,2,2, EF6 to 0,1,1,1,2"
)
```
After running this model, we see the disordering for `EF6` has been resolved! All single items now have ordered thresholds!
```{r adult-t1r4-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode4/PImap.png")
```
We will also check the other files to make sure our other Rasch Model assumptions have been maintained. We check `LID_plot.pdf` and see we still have achieved item independence. We also check the scree plot in `parallel_analysis_scree.pdf` to see if we still have unidimensionality. Finally, we also check `item_fit.csv` and `Targeting.csv` and see that the values are still acceptable in these files as well.
All of our Rasch Model assumptions have been reasonably attained, so this means we can stop! We have finished our Rasch Analysis for this set of questions. The data with the scores is in the file `Data_final.csv`. We will discuss what to do with these scores in later sections.
# Best practices
Go to the [Best Practices in Rasch Analysis](c5_best_practices_EN.html) vignette to read more about general rules to follow.
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c3_rasch_adults_EN.Rmd
|
---
title: "3 - Análisis Rasch con los datos de adultos de MDS"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{3 - Análisis Rasch con los datos de adultos de MDS}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
# Estructura
Para realizar el Análisis Rasch para adultos, solo se necesita usar una función: `rasch_mds()`. Esto se conoce como una "función de envoltura" (_wrapper function_). Una función de envoltura es una función que facilita el uso de otras funciones. En nuestro caso, `rasch_mds()` utiliza todas las otras funciones `rasch_*()` para realizar el análisis. Estas otras funciones `rasch_*()` usadas para adultos son:
* `rasch_DIF()`
* `rasch_drop()`
* `rasch_factor()`
* `rasch_model()`
* `rasch_rawscore()`
* `rasch_recode()`
* `rasch_rescale()`
* `rasch_split()`
* `rasch_testlet()`
Solo necesitas usar la función `rasch_mds()`. Pero si desea realizar su análisis de una manera más personalizada, puede trabajar directamente con las funciones internas.
# Salida
Después de cada iteración del Modelo Rasch, los códigos anteriores producen una variedad de archivos que le dirán qué tan bien los datos se ajustan a las suposiciones del modelo en esta iteración. Los archivos más importantes son los de abajo. Explicaremos cada uno en detalle a través de nuestro ejemplo.
* `LID_plot.pdf` - muestra elementos correlacionados
* `LID_above_0.2.csv` - correlaciones entre elementos correlacionados
* `parallel_analysis_scree.pdf` - gráfico de scree
* `bifactor_analysis.pdf` - cargas de factores
* `PImap.pdf`- ubicaciones de personas y ítems, ordenamiento de umbrales
* `item_fit.xlsx` - ajuste de ítems
* `Targetting.csv` - fiabilidad del modelo
# Argumentos de `rasch_mds()`
En esta sección examinaremos cada argumento de la función `rasch_mds()`. El archivo de ayuda para la función también describe los argumentos. Se puede acceder a los archivos de ayuda para las funciones en `R` escribiendo `?` antes del nombre de la función, de esta manera:
```{r rasch-mds-help}
?rasch_mds
```
A continuación se muestra un ejemplo de uso de la función `rasch_mds()`:
```{r rasch-mds-example}
rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run"
)
```
El primer argumento es `df`. Este argumento es para los datos. El objeto de datos debe ser datos de encuestas individuales, con una fila por persona. Aquí los datos se almacenan en un objeto `df_adults`, que es un base de datos incluido en el paquete` whomds`. Para obtener más información sobre `df_adults`, consulta su archivo de ayuda ejecutando:`?df_adults`
El segundo argumento es `vars_metric`, que es igual a un vector de caracteres de los nombres de columna para los elementos a usar en el Análisis de Rasch. Aquí es igual a `paste0("EF", 1:12)`, que es un vector de caracteres de longitud 12 de los nombres de columna `EF1`, `EF2`, ... `EF11` y `EF12`.
El siguiente argumento es `vars_id`, que es el nombre de la columna utilizada para identificar de forma única a los individuos. Aquí la columna de ID se llama `HHID`.
El siguiente argumento es `vars_DIF`. Es igual a un vector de caracteres con los nombres de las columnas que se utilizan para analizar el funcionamiento diferencial de elementos (DIF). DIF se tratará con más detalle en las secciones posteriores. Aquí `vars_DIF` es igual a un vector de caracteres de longitud dos que contiene el nombre de las columnas `"sex"` y `"age_cat"`.
El siguiente argumento es `resp_opts`. Este es un vector numérico con las posibles opciones de respuesta para `vars_metric`. En esta encuesta, las preguntas `EF1` a `EF12` tienen las opciones de respuesta 1 a 5. Entonces, `resp_opts` es igual a un vector numérico de longitud 5 con los valores `1`, `2`,` 3`, `4` y `5`.
El siguiente argumento es `max_NA`. Este es un valor numérico para el número máximo de valores faltantes permitidos para que una persona aún se tenga en cuenta en el análisis. El Análisis de Rasch puede manejar a personas que tienen algunos valores faltantes, pero demasiados causarán problemas en el análisis. En general, todos los individuos en la muestra deben tener menos del 15% de valores faltantes. Aquí `max_NA` es `2`, lo que significa que se permite que los individuos tengan un máximo de dos valores faltantes de las preguntas en `vars_metric` para que aún se incluyan en el análisis.
El siguiente argumento es `print_results`, que es `TRUE` o `FALSE`. Cuando es `TRUE`, los archivos se guardarán en su computadora con los resultados de la iteración Rasch. Cuando es `FALSE`, los archivos no se guardarán.
El siguiente argumento es `path_parent`. Esta es una cadena con la ruta a la carpeta donde se guardarán los resultados de múltiples modelos, asumiendo que `print_results` es `TRUE`. La carpeta en `path_parent` contendrá carpetas separadas con los nombres especificados en `model_name` en cada iteración. En la ejecución de la función anterior, todos los resultados se guardarán en el Desktop. Ten en cuenta que al escribir rutas para `R`, todas las barras deberían ser: `/ `(NO `\`). Asegúrate de incluir un `/` final en el final de la ruta.
El siguiente argumento es `model_name`. Esto es igual a una cadena donde le das un nombre del modelo que estás ejecutando. Este nombre se usará como el nombre de la carpeta donde se guardará toda la salida en su computadora, si `print_results` es `TRUE`. El nombre que le des debe ser corto pero informativo. Por ejemplo, puede llamar a su primera ejecución "Start", como se llama aquí. Si creas un testlet en su segunda ejecución, quizás puedas llamarlo "Testlet1", etc. Elije lo que sea significativo para tí.
Los siguientes argumentos son `testlet_strategy`, `recode_strategy`, `drop_vars` y `split_strategy`. Estos son argumentos que controlan cómo se usan los datos en cada iteración del Modelo Rasch. Cada uno será discutido con más detalle en secciones posteriores. Aquí están todos configurados en `NULL`, lo que significa que no se usan en la iteración del Análisis Rasch que se muestra aquí.
El último argumento es `comment`. Esto es igual a una cadena en la que puedes escribir cierta información de texto libre sobre la iteración actual para que cuando veas los resultados más adelante puedas recordar lo que hiciste y por qué lo hiciste. Es mejor ser más detallado, porque olvidarás por qué eligiste ejecutar el modelo de esta manera en particular. Este comentario se guardará en un archivo `Comment.txt`. Aquí el comentario es solo `"Initial run"`.
# Ajustar los datos
A continuación, discutiremos los argumentos que dan instrucciones sobre cómo ajustar los datos. Es posible que estas partes no sean del todo significativas ahora, pero lo serán aún más después de que pasemos por un ejemplo.
## Crear testlets
Si deseas crear testlets, es decir, sumar los ítems en súper-ítems para corregir la dependencia de los ítems, luego pasa una estrategia para hacer testlets al argumento `testlet_strategy`. `testlet_strategy` es una lista con un elemento de la lista por testlet que deseas crear. Cada elemento de la lista debe ser un vector de caracteres de los nombres de columna para usar para el testlet. Opcionalmente, puede nombrar los elementos de la lista para dar nombres personalizados a los nuevos testlets. Sin nombres especificados, los nuevos testlets serán los nombres de columna originales separados por "_".
Por ejemplo, imagine que desea hacer dos testlets: un testlet de las variables `EF4`, `EF6` y `EF8` con un nuevo nombre de `new`, y otro testlet de `EF5` y `EF7`, sin un nuevo nombre especificado. Entonces deberías especificar `testlet_strategy` como lo siguiente:
```{r rasch-mds-testlet}
rasch_mds(
...,
testlet_strategy = list(
new = c("EF4", "EF6", "EF8"),
c("EF5", "EF7")
)
)
```
## Recodificación
Si deseas recodificar las opciones de respuesta, es decir, cambiar las opciones de respuesta para crear un ordenamiento estocástico, entonces pasa una estrategia para la recodificación al argumento `recode_strategy`. `recode_strategy` toma la forma de una lista nombrada, con un elemento de la lista por estrategia de recode. Los nombres de la lista son los grupos de nombres de columna que se deben usar para cada estrategia de recodificación, separados solo por ",". Cada elemento de la lista es un vector numérico que proporciona las nuevas opciones de respuesta para asignar las variables.
Por ejemplo, si desea combinar las dos últimas opciones de respuesta de las variables `EF1` y `EF2`, y combinar las dos primeras opciones de respuesta de `EF3`, entonces establecería `recode_strategy` como lo siguiente:
```{r rasch-mds-recode}
rasch_mds(
...,
recode_strategy = list(
"EF1,EF2" = c(0,1,2,3,3),
"EF3" = c(0,0,1,2,3)
)
)
```
## Eliminar variables
Si deseas eliminar cualquier ítem de tu análisis, tal vez en el caso de un ajuste extremadamente deficiente, configura `drop_vars` como un vector de caracteres de los nombres de columna para que se eliminen del análisis.
Por ejemplo, si los ítems `EF4` y `EF7` eran ítems extremadamente mal ajustados, entonces podrían eliminarse del análisis especificando `drop_vars` como lo siguiente:
```{r rasch-mds-drop}
rasch_mds(
...,
drop_vars = c("EF4", "EF7")
)
```
## Dividir
Si deseas dividir los ítems por subgrupos, tal vez en el caso de funcionamiento diferencial de ítems (DIF) alto, a continuación, das las instrucciones para su estrategia de división en el argumento `split_strategy`.
La división de ítems implica tomar un solo ítem y separarlo en dos o más ítems para diferentes grupos. Por ejemplo, si quisiéramos dividir un ítem `var` por sexo, crearíamos dos ítems:` var_Male` y `var_Female`. `var_Male` sería equivalente a `var` para todos los encuestados que son hombres, y `NA` para los encuestados que son mujeres. `var_Female` sería equivalente a `var` para todos los encuestados que son mujeres, y `NA` para los encuestados que son hombres.
`split_strategy` toma la forma de una lista nombrada. Hay un elemento de la lista por variable para la que divides. Cada elemento de la lista debe ser un vector de caracteres de los nombres de columna para dividir. Los nombres de la lista son las variables para las que divides cada grupo de variables.
Por ejemplo, si quisiéramos dividir las variables `EF1` y `EF2` por `sex`, y dividir `EF3` por la categoría de edad `age_cat`, entonces especificaríamos `split_strategy` como la siguiente:
```{r rasch-mds-split}
rasch_mds(
...,
split_strategy = list(
sex = c("EF1", "EF2"),
age_cat = c("EF3")
)
)
```
Sin embargo, debido a que esperamos una cierta cantidad de DIF al medir la discapacidad, especialmente por sexo y edad, rara vez usamos esta opción. Para no realizar ninguna división, deje `split_strategy` como su valor predeterminado de `NULL`.
# Ejemplo
A continuación, crearemos una métrica utilizando los datos de muestra `df_adults` utilizando las preguntas de factores ambientales (EF, por sus siglas en inglés) del cuestionario. Estas son las preguntas `EF1` a `EF12`.
## Start
Comenzaremos intentando ejecutar el modelo sin realizar ningún ajuste en nuestros datos. Para ejecutar este modelo, ejecuta un comando que sea similar a este:
```{r adult-start-example}
start <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run"
)
```
Es posible que el código que ejecutas no sea exactamente el mismo, porque, por ejemplo, el directorio que usas para `path_parent` será específico para tu máquina, y puedes elegir un `model_name` y `comment` diferentes para tu modelo.
Al ejecutar este comando, se imprime los resultados en tu máquina (porque `print_results` es `TRUE`), también está guardando algo de salida en un objeto en el entorno global de `R` llamado `start`. Este objeto es una lista con tres elementos: uno llamado `df`, uno llamado `vars_metric` y uno llamado `df_results`. `df` contiene los datos con las variables transformadas utilizadas para crear la puntuación y las puntuaciones redimensionadas. `vars_metric` es un vector de caracteres de los nombres de `vars_metric` después de transformar las variables. `df_results` es un marco de datos con una fila y una columna para cada una de las estadísticas principales para evaluar las suposiciones del modelo de Rasch. `df_results` de múltiples modelos se pueden combinar para crear un marco de datos que le permita comparar rápidamente diferentes modelos.
No es necesario guardar la salida de `rasch_mds()` en un objeto en el entorno global, pero facilita la manipulación de la salida resultante para determinar qué ajustes hacer a tus datos en la siguiente iteración.
Después de ejecutar este comando, se guardarán varios archivos en la carpeta que especificó. Va a la carpeta `path_parent`, y verás una nueva carpeta con el nombre que especificó en `model_name`. Dentro de esa carpeta, habrá muchos archivos. Nos centraremos en los más importantes. Lee nuevamente la Sección \@ref(reparación) para ver cómo los diferentes suposiciones del Modelo Rasch se afectan entre sí y para comprender por qué revisaremos los archivos importantes en este orden particular.
Primero revisaremos la dependencia local del artículo de los artículos. Podemos verificar esto mirando los archivos `LID_plot.pdf` y` LID_above_0.2.csv`. `LID_above_0.2.csv` da las correlaciones de los residuos que están por encima de 0.2, y `LID_plot.pdf` es una visualización de estas correlaciones. De estos archivos, podemos ver que los elementos `EF11` y `EF12` están correlacionados. El valor de la correlación es aproximadamente 0.47. Estos dos elementos tienen que ver con la forma en que se facilita o dificulta el trabajo (`EF11`) y la escuela (`EF12`). Conceptualmente, tiene sentido que las respuestas de las personas a estas dos preguntas estén relacionadas. Nos ocuparemos de esta correlación en la próxima iteración del modelo.
```{r adult-start-LID, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/LID_plot.png")
```
A continuación, investigaremos la unidimensionalidad del modelo analizando el archivo `parallel_analysis_scree.pdf`. Esto es lo que se conoce como una "gráfico scree". Un gráfico scree muestra los valores propios (_eigenvalues_) de nuestro modelo e indica cuántas dimensiones subyacentes tenemos en nuestro cuestionario. Con este gráfico, esperamos ver una disminución muy marcada después del primer valor propio a la izquierda, y que el segundo valor propio caiga por debajo de la línea verde del _"Parallel Analysis"_. Esto significaría que tenemos una dimensión subyacente que es muy sólida en nuestros datos, y cualquier otra dimensión que se calcule tendrá muy poca influencia en el modelo. En nuestro gráfico, vemos una disminución muy marcada después del primer valor propio, y la línea verde cruza la línea negra después del segundo factor. Esto es suficiente para confirmar la unidimensionalidad para el modelo.
```{r adult-start-scree, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/parallel_analysis_scree.png")
```
Otro archivo importante que podemos examinar es el `PImap.pdf`. Este es el "Mapa persona-ítem", y muestra personas y ítems en el mismo continuo. El eje horizontal en la parte inferior de la figura es este continuo, etiquetado como la "dimensión latente". La parte superior de la figura está etiquetada como "distribución de parámetros de persona". Esta es la distribución de las puntuaciones de las personas en el continuo. Puede mostrarle si, por ejemplo, tiene más personas en un extremo de la escala u otro.
```{r adult-start-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Start/PImap.png")
```
La parte más grande de esta figura muestra dónde se ubican los umbrales para cada elemento en el continuo. Los umbrales están etiquetados con números: el primer umbral está etiquetado como "1", el segundo está etiquetado como "2", y así sucesivamente. El punto negro es el promedio de las ubicaciones de todos estos umbrales. Las estrellas en el lado derecho de la figura indican si los umbrales están o no fuera de orden. Por ejemplo, puedes ver para `EF1`, los umbrales están ordenados 2, 4, 1, 3 que están claramente fuera de orden. De hecho, en este caso, todos los elementos tienen umbrales fuera de orden. Es probable que esto sea algo de lo que tengamos que ocuparnos más adelante, pero primero nos encargaremos de la dependencia del artículo.
Otro archivo importante que podemos analizar es `item_fit.csv`. Este archivo da las estadísticas de ajuste para cada elemento. Las dos estadísticas de ajuste utilizadas aquí son _"outfit"_ e _"infit"_, que se muestran en las columnas `i.outfitMSQ` e `i.infitMSQ`. Ambos son similares, pero el outfit es más sensible a los valores atípicos. En general, esperamos que estas cifras estén lo más cerca posible de 1. Si están por debajo de 1, entonces indica que el ítem está _"overfitting"_. _"Overfit"_ se refiere a la situación cuando los ítems se ajustan "demasiado cerca" al modelo. Si estas estadísticas son mayores que 1, entonces indican que los ítems son _"underfitting"_. _"Underfit"_ se refiere a la situación cuando los ítems no se ajustan bien al modelo. _Underfit_ es más grave que _overfit_. Esperamos en general que el _infit_ y el _outfit_ de los artículos estén entre 0.5 y 1.5. Si son menos de 0.5, las medidas de fiabilidad para el modelo pueden ser engañosamente altas, pero aún se pueden usar las puntuaciones. Si están entre 1.5 y 2.0, esta es una señal de advertencia de que los ítems pueden estar causando problemas y usted podría comenzar a considerar ajustar los datos para mejorar el ajuste. Si son mayores que 2.0, las puntuaciones calculadas pueden estar significativamente distorsionadas y se deben tomar medidas para ajustar los datos para mejorar el ajuste.
En este caso, todos los artículos tienen estadísticas infit y outfit entre 0.5 y 1.5, lo que es bueno.
Para analizar el ajuste global del modelo, podemos abrir el archivo `Targeting.csv`. Este archivo proporciona la media y la desviación estándar de las capacidades de la persona y de las dificultades del ítems. También proporciona el "índice de separación de personas" o PSI por sus siglas en inglés, que es una medida de fiabilidad para el modelo. Esperamos que este valor sea lo más cercano posible a 1. En general, es aceptable si esta cifra está por encima de 0.7, aunque esperamos obtener valores tan altos como 0.8 o 0.9. Para nuestro modelo aquí, nuestro PSI es 0.82, lo cual es muy bueno.
## Testlet1
Con nuestra próxima iteración del modelo, intentaremos abordar la alta dependencia de elementos entre los elementos `EF11` y `EF12`. Haremos esto creando un testlet entre estos dos elementos. Hacemos esto cambiando el argumento `testlet_stratey` como se muestra a continuación. Le hemos dado al nuevo testlet el nombre de `workschool`, pero puedes nombrarlo como desees.
```{r adult-t1-example}
testlet1 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25)"
)
```
Después de ejecutar este modelo, obtenemos un error:
```{r adult-t1-error, echo=FALSE, eval=TRUE, message=TRUE}
message("Error in tapply(1L:ncol(X01beta), mt_ind, function(xin) { :
arguments must have same length ")
```
Este error es un poco extraño. Pero a veces surgen errores como este a causa de demasiadas `NA` en los datos o si no hay suficientes personas que apoyen todas las opciones de respuesta posibles. Veamos el archivo `response_freq.csv` para ver cómo se distribuyen las opciones de respuesta. Podemos ver en este archivo que hay muchos respaldos para todas las opciones de respuesta para todas las preguntas excepto para nuestro nuevo testlet `workschool`, que solo tiene 1 persona con una respuesta de 6, y nadie con las repuestas posibles de 5, 7 o 8. Quizás esto es lo que está causando el problema.
### Más sobre la recodificación
Primero vamos a discutir la recodificación con un poco más de detalle.
Cada pregunta con `n` opciones de respuesta tendrá `n-1` umbrales. El primer umbral (etiquetado con un "1" en el mapa persona-ítem) es el punto entre la primera y la segunda opción de respuesta donde un encuestado tiene la misma probabilidad de elegir cualquiera de estas opciones de respuesta; el segundo umbral (etiquetado con un "2" en el mapa persona-ítem) es el punto entre la segunda y la tercera opción de respuesta donde un encuestado tiene la misma probabilidad de elegir cualquiera de estas opciones de respuesta; y así.
Queremos que nuestros umbrales en el mapa persona-ítem estén en el orden correcto: 1, 2, 3, 4 y así sucesivamente. Los umbrales desordenados indican un problema con nuestros ítems Por ejemplo, si los umbrales se enumeran en el orden 1, 2, 4, 3, entonces los datos nos dicen que es más probable que alguien supere el cuarto umbral antes del tercer umbral, lo cual no tiene sentido. Recodificamos las opciones de respuesta para crear menos umbrales, de modo que sea más fácil para ellos estar en orden.
Las funciones para realizar el Análisis Rasch cambian nuestras opciones de respuesta para que comiencen con 0. Esto se hace porque las funciones para realizar el análisis lo requieren. Por ejemplo, nuestra encuesta tiene preguntas que tienen opciones de respuesta que van del 1 al 5, pero internamente la función cambia estas opciones de respuesta para que varíen de 0 a 4. En consecuencia, es un poco más sencillo interpretar qué opciones de respuesta necesitan ser recodificadas directamente de las etiquetas de los umbrales. Por ejemplo, si un ítem está desordenado en el patrón 1, 2, 4, 3, esto significa que los umbrales 4 y 3 están fuera de orden. Esto también significa que podemos recodificar las opciones de respuesta transformadas 4 y 3 para combinar estos umbrales.
Cuando queremos recodificar un ítem, proporcionamos a la función instrucciones sobre a qué asignar las opciones de respuesta. Por ejemplo, digamos que un ítem `var` tiene umbrales desordenados en el patrón 1, 2, 4, 3. Ahora queremos combinar el cuarto y el tercer umbral para que el ítem se ordene. `var` tiene opciones de respuesta que van de 0 a 4 (después de haber cambiado del original por una sustracción de 1), por lo que queremos combinar las opciones de respuesta 3 y 4 para el ítem para combinar estos dos umbrales. Hacemos esto diciendo a la función que mapee las opciones de respuesta actuales de 0, 1, 2, 3, 4 a 0, 1, 2, 3, 3. Esto significa que todas las respuestas de "4" ahora se recodifican como "3" . Ahora solo tendremos 4 opciones de respuesta diferentes, lo que significa que tendremos 3 umbrales diferentes, que ahora esperamos que estén en el orden correcto.
Esto se aclarará a medida que trabajemos en el ejemplo.
## Testlet1_Recode1
En la siguiente iteración, intentaremos recodificar las opciones de respuesta de nuestro testlet para que el modelo pueda ejecutarse.
Ejecutaremos el comando como abajo:
```{r adult-t1r1-example}
testlet1_recode1 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode1",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5"
)
```
La diferencia entre el modelo Testlet1 y este modelo es que ahora hemos agregado una estrategia de recodificación. Recodificaremos las opciones de respuesta del testlet `workschool` a 0,1,2,3,4,5,6,7,7. Esto significa que todas las opciones de respuesta permanecerán igual, excepto las opciones 5 a 8 están combinadas.
Después de ejecutar el comando, vemos que el modelo se puede calcular normalmente.
Primero verificamos `LID_plot.pdf` para ver si hemos podido eliminar la correlación del elemento. En este archivo, vemos el mensaje _"No LID found"_, lo que significa que nuestra estrategia de prueba fue efectiva.
A continuación, verificamos el gráfico scree en el archivo `parallel_analysis_scree.pdf` para asegurarnos de que se mantiene nuestra unidimensionalidad. De hecho, parece muy similar al modelo inicial, que es lo que esperamos.
A continuación, verificamos el mapa persona-ítem en `PImap.pdf`. Podemos ver en este archivo que todos los elementos aún están desordenados, por lo que es probable que esto sea lo próximo que tengamos que cuidar en la próxima iteración del modelo.
```{r adult-t1r1-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode1/PImap.png")
```
Finalmente verificaremos el ajuste del ítem y el ajuste general del modelo en `item_fit.csv` y `Targeting.csv`, respectivamente. Podemos ver que todos estos valores siguen siendo buenos: cada ítem aún tiene estadísticas de infit y outfit entre 0.5 y 1.5, y el PSI aún es 0.82.
## Testlet1_Recode2
A continuación, intentaremos recodificar elementos para crear umbrales ordenados. Estamos más preocupados por tener los artículos individuales (todo lo que no es un testlet) ordenados.
Hay varias formas de elegir la estrategia de recodificación. En general, desea hacer la cantidad mínima de recodificación necesaria para alcanzar los umbrales ordenados. Primero intentaremos combinar los dos primeros umbrales para todos los elementos que no sean el testlet. Veremos para qué elementos funciona esto y probaremos una nueva estrategia en la siguiente iteración para los elementos en los que no funcionó.
```{r adult-t1r2-example}
testlet1_recode2 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode2",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,3)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,3"
)
```
Podemos ver en el nuevo mapa persona-ítem que esta estrategia no funcionó para ninguno de los ítems. Así que intentaremos una nueva estrategia en la próxima iteración.
```{r adult-t1r2-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode2/PImap.png")
```
También podemos verificar los otros archivos para ver si alguna otra suposición del Modelo Rasch ha sido violada con esta estrategia de recodificación. Pero debido a que estamos cambiando nuestra estrategia completamente en la próxima iteración, no es necesario prestar demasiada atención a los otros archivos para esta iteración.
## Testlet1_Recode3
Desde el mapa persona-ítem para el modelo de inicio, podemos ver que nuestros ítems están desordenados de una manera un poco complicada: muchos ítems tienen umbrales en los órdenes 2, 4, 1, 3 o 2, 3, 4, 1. Por lo general, si un ítem tiene umbrales desordenados en un patrón bastante sencillo (por ejemplo, 1, 2, 4, 3 o 2, 1, 3, 4), entonces la estrategia de recodificación es sencilla. Por ejemplo, con un desorden de 1, 2, 4, 3, está claro que las opciones de respuesta 3 y 4 deberían estar combinadas. Con un desorden de 2, 1, 3, 4, entonces las opciones de respuesta de 1 y 2 deberían combinarse.
En nuestro caso, el desorden es bastante complicado, por lo que la estrategia de recodificación es menos directa y probablemente tendrá que ser más extrema. En esta iteración, intentaremos colapsar dos conjuntos de opciones de respuesta: colapsaremos 1 con 2 y 3 con 4, como se muestra a continuación.
```{r adult-t1r3-example}
testlet1_recode3 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode3",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF6,EF7,EF8,EF9,EF10" = c(0,1,1,2,2)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else 0,1,1,2,2"
)
```
¡Podemos ver con esta estrategia de recodificación que los umbrales ahora están ordenados para la mayoría de los artículos! El único elemento para el que no funcionó es `EF6`, para lo cual tendremos que probar una estrategia diferente en la próxima iteración.
```{r adult-t1r3-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode3/PImap.png")
```
Avanzamos en nuestro desordenamiento de umbrales, pero debemos asegurarnos de que las otras suposiciones del Modelo Rasch no se hayan violado con esta nueva estrategia. Verificamos `LID_plot.pdf` y vemos que todavía hemos logrado la independencia del elemento. También verificamos el gráfico scree en `parallel_analysis_scree.pdf` para ver si todavía tenemos unidimensionalidad. Finalmente, también verificamos `item_fit.csv` y `Targeting.csv` y vemos que los valores también son aceptables en estos archivos. Así que procederemos con una estrategia de recodificación alterada en la siguiente iteración.
## Testlet1_Recode4
Todavía tenemos dos elementos desordenados: `EF6` y `workschool`. Por lo general, no nos preocupa que los testlets se desordenen porque no son elementos incluidos originalmente en el cuestionario. Podríamos recodificar `workschool` si el ajuste del ítem fuera muy pobre, pero en nuestro modelo mantiene el ajuste adecuado del ítem según las estadísticas de _infit_ y _outfit_, por lo que no lo recodificaremos.
Por lo tanto, en esta iteración solo intentaremos resolver el desorden de `EF6`. Intentaremos combinar las tres opciones de respuesta del medio, como se muestra a continuación.
```{r adult-t1r4-example}
testlet1_recode4 <- rasch_mds(
df = df_adults,
vars_metric = paste0("EF", 1:12),
vars_id = "HHID",
vars_DIF = c("sex", "age_cat"),
resp_opts = 1:5,
max_NA = 2,
print_results = TRUE,
path_parent = "/Users/lindsaylee/Desktop/",
model_name = "Testlet1_Recode4",
testlet_strategy = list(workschool = c("EF11", "EF12")),
recode_strategy = list(workschool = c(0,1,2,3,4,5,5,5,5),
"EF1,EF2,EF3,EF4,EF5,EF7,EF8,EF9,EF10" = c(0,1,1,2,2),
EF6 = c(0,1,1,1,2)),
drop_vars = NULL,
split_strategy = NULL,
comment = "Testlet: EF11,EF12 (LID>0.25); Recode: workschool to 0,1,2,3,4,5,5,5,5, everything else except EF6 to 0,1,1,2,2, EF6 to 0,1,1,1,2"
)
```
Después de ejecutar este modelo, vemos que se ha resuelto el desorden para `EF6`. ¡Todos los artículos individuales ahora tienen umbrales ordenados!
```{r adult-t1r4-PI, echo=FALSE, eval=TRUE}
include_graphics("Images/ExampleRasch_EF/Testlet1_Recode4/PImap.png")
```
También revisaremos los otros archivos para asegurarnos de que se hayan mantenido nuestros otras suposiciones del Modelo Rasch. Verificamos `LID_plot.pdf` y vemos que todavía hemos logrado la independencia del ítem. También verificamos el gráfico scree en `parallel_analysis_scree.pdf` para ver si todavía tenemos unidimensionalidad. Finalmente, también verificamos `item_fit.csv` y `Targeting.csv` y vemos que los valores también son aceptables en estos archivos.
Todas nuestras suposiciones del Modelo Rasch se han alcanzado razonablemente, ¡así que esto significa que podemos terminarnos! Hemos terminado nuestro Análisis Rasch para este conjunto de preguntas. Los datos con las puntuaciones se encuentran en el archivo `Data_final.csv`. Discutiremos qué hacer con estos puntajes en secciones posteriores.
# Mejores prácticas
Lea el vignette [Mejores prácticas con Análisis Rasch](c5_best_practices_ES.html) para aprender más sobre principios generales para usar.
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c3_rasch_adults_ES.Rmd
|
---
title: "4 - Rasch Analysis for MDS data from children"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{4 - Rasch Analysis for MDS data from children}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
As already mentioned, a different process must be used to calculate disability scores for children. Children at different ages are incredibly different, and thus have different items pertaining to them in the questionnaire.
In the Capacity section of the children questionnaire, items are applied to all children aged 2 to 17, without age-specific filters. In this case, a multigroup analysis must be performed. This is essentially the same as performing a Rasch Model as for adults, however we alert the program to the fact that we have very different groups responding to the questionnaire--that is, different age groups. We use the age groups 2 to 4, 5 to 9, and 10 to 17.
In the Performance section of the children questionnaire, there is a set of common questions for all children and a set of questions with age-specific filters. In this case, a multigroup analysis is first performed on all the common items, as with the Capacity questions. Then this multigroup model is used to calibrate an additional score using all of the age-specific questions. This is called "anchoring"--we are anchoring the results of the age-specific questions on the results from the common set of questions. This must be done in order to make the disability scores obtained for children comparable across age groups.
# Structure
The `whomds` package also contains functions to perform Rasch Anaylsis for children.
To perform Rasch Analysis for children, only one function needs to be used: `rasch_mds_children()`. This is a wrapper function, like `rasch_mds()` for adults. `rasch_mds_children()` utilizes all the other `rasch_*()` functions to perform the analysis. These other `rasch_*()` functions used for children are:
* `rasch_df_nest()`
* `rasch_drop()`
* `rasch_factor()`
* `rasch_model_children()`
* `rasch_quality_children()`
* `rasch_quality_children_print()`
* `rasch_recode()`
* `rasch_rescale_children()`
* `rasch_split()`
* `rasch_split_age()`
* `rasch_testlet()`
You only need to use the function `rasch_mds_children()`. But if you wanted to perform your analysis in a more customized way, you could work with the internal functions directly.
# Output
After each iteration of the Rasch Model, the codes above produce a variety of files that will tell you how well the data fit the assumptions of the model at this iteration. The most important files are the ones below. We will explain each in detail below.
* Local item dependence spreadsheets and plots:
+ `LID_plot_Multigroup.pdf` and `LID_above_0.2_Multigroup.csv` - shows correlated items for multigroup model
+ `LID_plotAge2to4.pdf` and `LID_above_0.2_Age2to4.csv` - shows correlated items for ages 2 to 4 for anchored model
+ `LID_plotAge5to9.pdf` and `LID_above_0.2_Age5to9.csv` - shows correlated items for ages 5 to 9 for anchored model
+ `LID_plotAge10to17.pdf` and `LID_above_0.2_Age10to17.csv` - shows correlated items for ages 10 to 17 for anchored model
* Scree plots:
+ `ScreePlot_Multigroup_PCM2.pdf` - scree plot for multigroup model
+ `ScreePlot_Anchored_PCM2_Age2to4.pdf` - scree plot for ages 2 to 4 for anchored model
+ `ScreePlot_Anchored_PCM2_Age5to9.pdf` - scree plot for ages 5 to 9 for anchored model
+ `ScreePlot_Anchored_PCM2_Age10to17.pdf` - scree plot for ages 10 to 17 for anchored model
* Locations of persons and items:
+ `WrightMap_multigroup.pdf` - locations of persons and items for multigroup model
+ `WrightMap_anchored_Age2to4.pdf` - locations of persons and items for ages 2 to 4 for anchored model
+ `WrightMap_anchored_Age5to9.pdf` - locations of persons and items for ages 5 to 9 for anchored model
+ `WrightMap_anchored_Age10to17.pdf` - locations of persons and items for 10 to 17 for anchored model
* Item fit:
+ `PCM2_itemfit_multigroup.xlsx` - item fit for multigroup model
+ `PCM2_itemfit_anchored.xlsx` - item fit for anchored model
* Model fit:
+ `PCM2_WLE_multigroup.txt` - reliability of model for multigroup model
+ `PCM2_WLE_anchored.txt` - reliability of model for anchored model
# Arguments of `rasch_mds_children()`
In this section we will examine each argument of the function `rasch_mds_children()`. The help file for the function also describes the arguments. Help files for functions in `R` can be accessed by writing `?` before the function name, like so:
```{r rasch-mds-children-help}
?rasch_mds_children
```
Below is an example of a use of the function `rasch_mds_children()`:
```{r rasch-mds-children-example}
rasch_mds_children(df = df_children,
vars_id = "HHID",
vars_group = "age_cat",
vars_metric_common = paste0("child", c(1:10)),
vars_metric_grouped = list(
"Age2to4" = paste0("child", c(12,15,16,19,20,24,25)),
"Age5to9" = paste0("child", c(11,13,14,17,18,20,21,22,23,24,25,27)),
"Age10to17" = paste0("child", c(11,13,14,17,18,20,21,22,23,25,26,27))),
TAM_model = "PCM2",
resp_opts = 1:5,
has_at_least_one = 4:5,
max_NA = 10,
print_results = TRUE,
path_parent = "~/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run")
```
The first argument is `df`. This argument is for the data. The data object should be individual survey data, with one row per individual. Here the data is stored in an object `df_children`, which is a data set included in the `whomds` package. To find out more about `df_children` please look at its help file by running: `?df_children`
The next argument is `vars_id`, which is the name of the column used to uniquely identify individuals. Here the ID column is called `HHID`.
The next argument is `vars_group`, which is a string with the column name identifying groups, specifically age groups in this case. Here the age group column is `age_cat`.
The next two arguments specify the variables used to build the metric.
`vars_metric_common` is a character vector with the names of the items that every individual in the same answers.
`vars_metric_grouped` is a named list of character vectors with the items to use in the Rasch Analysis per group from the variable specified in `vars_group`. The list should have names corresponding to the different groups (for example, `Age2to4`, `Age5to9` and `Age10to17`), and contain character vectors of the corrsponding items for each group.
If only `vars_metric_common` is specified, then a multigroup analysis will be performed. If `vars_metric_common` and `vars_metric_grouped` are both specified, then an anchored analysis will be performed. `vars_metric_grouped` cannot be specified on its own.
The next argument is `TAM_model`. This is a string that identifies which Item Response Theory model to use. This value is passed to the function from the `TAM` package used to calculate the Rasch Model. The default is `"PCM2"`, which specifies the Rasch Model.
The next argument is `resp_opts`. This is a numeric vector with the possible response options for `vars_metric_common` and `vars_metric_grouped`. In this survey, the questions have response options 1 to 5. So here `resp_opts` is equal to a numeric vector of length 5 with the values `1`, `2`, `3`, `4` and `5`.
The next argument is `has_at_least_one`. This is a numeric vector with the response options that a respondent must have at least one of in order to be included in the metric calculation. This argument is required because often Rasch Analysis of children data is more difficult because of the extreme skewness of the responses. For this reason, it is often advisable to build a scale only with the respondents on the more severe end of the disability continuum, for example only with those respondents who answered 4 or 5 to at least one question. By specifying `has_at_least_one`, the function will only build a scale among those who answered `has_at_least_one` in at least one question from `vars_metric_common` and `vars_metric_grouped`. The default is `4:5`, which means the scale will be created only with children who answered 4 or 5 to at least one question in `vars_metric_common` and `vars_metric_grouped`. The scores created can be reunited with the excluded children post-hoc.
The next argument is `max_NA`. This is a numeric value for the maximum number of missing values allowed for an individual to be still be considered in the analysis. Rasch Analysis can handle individuals having a few missing values, but too many will cause problems in the analysis. In general all individuals in the sample should have fewer than 15% missing values. Here `max_NA` is set to `10`, meaning individuals are allowed to have a maximum of ten missing values out of the questions in `vars_metric_common` and `vars_metric_grouped` to still be included in the analysis.
The next argument is `print_results`, which is either `TRUE` or `FALSE`. When it is `TRUE`, files will be saved onto your computer with results from the Rasch iteration. When it is `FALSE`, files will not be saved.
The next argument is `path_parent`. This is a string with the path to the folder where the results of multiple models will be saved, assuming `print_results` is `TRUE`. The folder in `path_parent` will then contain separate folders with the names specified in `model_name` at each iteration. In the function call above, all results will be saved on the Desktop. Note that when writing paths for `R`, the slashes should all be: `/` (NOT `\`). Be sure to include a final `/` on the end of the path.
The next argument is `model_name`. This is equal to a string where you give a name of the model you are running. This name will be used as the name of the folder where all the output will be saved on your computer, if `print_results` is `TRUE`. The name you give should be short but informative. For example, you may call your first run "Start", as it is called here, if you create a testlet in your second run perhaps you can call it "Testlet1", etc. Choose whatever will be meaningful to you.
The next arguments are `testlet_strategy`, `recode_strategy`, `drop_vars` and `split_strategy`. These are arguments that control how the data is used in each iteration of the Rasch Model. These are specified in the same way as for adult models, as described in the above sections. Here they are all set to `NULL`, which means they are not used in the iteration of Rasch Analysis shown here.
The last argument is `comment`. This is equal to a string where you can write some free-text information about the current iteration so that when you are looking at the results later you can remember what you did and why you did it. It is better to be more detailed, because you will forget why you chose to run the model in this particular way. This comment will be saved in a file `Comment.txt`. Here the comment is just `"Initial run"`.
# Example
## Differences from adult models
We have already discussed differences in the command required to compute the Rasch Model for children. To run this model, a different `R` package is available: `TAM`. This package can be more complicated to use than `eRm` (the package used for adults), but it allows for greater flexibility, and thus allows us to compute the multigroup and anchored analyses that we require.
With the `TAM` package, we are also able to compute different types of models. By default the `whomds` package computes results using the Partial Credit Model (the normal polytomous Rasch Model). The PCM is specified in `TAM` with the argument `TAM_model` set to `"PCM2"`.
Another option for `TAM_model` is `"GPCM"`, which tells the program to calculate a Generalized Partial Credit Model (GPCM). The GPCM differs from the PCM in that relaxes the uniform discriminating power of items. In other words, the GPCM allows for some items to be better able to identify people's abilities than other items.
We focus on PCM because we can obtain the scale we seek with this model.
## Improving model quality
As mentioned previously, generally the distribution of children's answers is much more heavily skewed towards the "no disability" end of the scale, so it is harder to build a quality metric. **Your model will be greatly improved if you only build it among children who indicate having some sort of level of problems in at least one of the domains.** This is why the default for the argument `has_at_least_one` of `rasch_children()` is `4:5`. We recommend keeping this default.
Collapsing response options may also improve the quality of your scale. We also recommend trying to build a scale where all items are recoded to 0,1,1,2,2--in other words, collapse the 2nd and 3rd response options and the 3rd and the 4th response options.
## Important output to examine
The output from the iterations of the Rasch Model for children using the WHO codes is very similar to that of the adult models. However, for the anchored models (for Performance) in particular, for most types of files there is a separate file for each age group. The quality of the model may vary across age groups, and all the information must be assessed simultaneously in order to determine how to adjust the data.
There are a couple of key differences we will highlight. In order to assess the model fit (targeting) of the model, open the file `PCM2_WLE.txt` and analyze the number after `"WLE Reliability = "`. WLE stands for "weighted likelihood estimator", and it corresponds to the PSI we used to assess model fit for the adult models. Similarly, for good model fit, we would like to see this number be at least greater than 0.7, ideally greater than 0.8 or more.
The person-item map is also different for the children model. The `TAM` package works with another package called `WrightMap` to produce, aptly called, Wright Maps. These are very similar to the person item maps we used previously, except the type of thresholds displayed are different. The Wright Map displays the "Thurstonian Thresholds", and these thresholds by definition will never be disordered. Hence is reasonable to generally ignore recoding response options for the children, unless you would like to collapse empty response options or attempt to improve the spread of the threshold locations to better target the persons' abilities.
As with adults, the new rescaled scores for children are located in the file `Data_final.csv`.
# Best practices
Go to the [Best Practices in Rasch Analysis](c5_best_practices_EN.html) vignette to read more about general rules to follow.
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c4_rasch_children_EN.Rmd
|
---
title: "4 - Análisis Rasch con los datos de niños de MDS"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{4 - Análisis Rasch con los datos de niños de MDS}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
Como ya se mencionó, se debe utilizar un proceso diferente para calcular los puntajes de discapacidad para los niños. Los niños de diferentes edades son increíblemente diferentes y, por lo tanto, tienen diferentes ítems pertenecientes a ellos en el cuestionario.
En la sección de Capacidad del cuestionario para niños, los ítems se aplican a todos los niños de 2 a 17 años, sin filtros específicos para cada edad. En este caso, se debe realizar un análisis multigrupo. Esto es esencialmente lo mismo que realizar un modelo de Rasch para adultos, sin embargo, alertamos al programa al hecho de que tenemos grupos muy diferentes que responden al cuestionario, es decir, diferentes grupos de edad. Usamos los grupos de edad 2 a 4, 5 a 9, y 10 a 17.
En la sección Desempeño del cuestionario para niños, hay un conjunto de preguntas comunes para todos los niños y un conjunto de preguntas con filtros específicos para cada grupo de edad. En este caso, primero se realiza un análisis multigrupo en todos los ítems comunes, como en las preguntas de Capacidad. Luego, este modelo multigrupo se usa para calibrar una puntuación adicional utilizando todas las preguntas específicas de la edad. Esto se llama "anclaje": estamos anclando los resultados de las preguntas específicas por edad en los resultados del conjunto común de preguntas. Esto debe hacerse para que los puntajes de discapacidad obtenidos para los niños sean comparables en todos los grupos de edad.
# Estructura
El paquete `whomds` también contiene funciones para realizar Rasch Anaylsis para niños.
Para realizar el Análisis Rasch para niños, solo se necesita usar una función: `rasch_mds_children()`. Esta es una función de envoltorio, como `rasch_mds()` para adultos. `rasch_mds_children()` utiliza todas las demás funciones `rasch_*()` para realizar el análisis. Estas otras funciones `rasch_*()` usadas para niños son:
* `rasch_df_nest()`
* `rasch_drop()`
* `rasch_factor()`
* `rasch_model_children()`
* `rasch_quality_children()`
* `rasch_quality_children_print()`
* `rasch_recode()`
* `rasch_rescale_children()`
* `rasch_split()`
* `rasch_split_age()`
* `rasch_testlet()`
Solo necesitas usar la función `rasch_mds_children()`. Pero si desea realizar su análisis de una manera más personalizada, puede trabajar directamente con las funciones internas.
# Salida
Después de cada iteración del Modelo Rasch, los códigos anteriores producen una variedad de archivos que le dirán qué tan bien los datos se ajustan a las suposiciones del modelo en esta iteración. Los archivos más importantes son los de abajo. Vamos a explicar cada uno en detalle a continuación.
* Hojas de cálculo y gráficos de dependencia local de ítems:
+ `LID_plot_Multigroup.pdf` y `LID_above_0.2_Multigroup.csv` - muestra ítems correlacionados para el modelo multigrupo
+ `LID_plotAge2to4.pdf` y `LID_above_0.2_Age2to4.csv` - muestra ítems correlacionados para edades de 2 a 4 para el modelo anclado
+ `LID_plotAge5to9.pdf` y `LID_above_0.2_Age5to9.csv` - muestra ítems correlacionados para edades de 5 a 9 para el modelo anclado
+ `LID_plotAge10to17.pdf` y `LID_above_0.2_Age10to17.csv` - muestra ítems correlacionados para edades de 10 a 17 para el modelo anclado
* Gráficos scree:
+ `ScreePlot_Multigroup_PCM2.pdf` - gráfico scree para el modelo multigrupo
+ `ScreePlot_Anchored_PCM2_Age2to4.pdf` - gráfico scree para para edades de 2 a 4 para el modelo anclado
+ `ScreePlot_Anchored_PCM2_Age5to9.pdf` - gráfico scree para para edades de 5 a 9 para el modelo anclado
+ `ScreePlot_Anchored_PCM2_Age10to17.pdf` - gráfico scree para para edades de 10 a 17 para el modelo anclado
* Ubicaciones de personas e ítems:
+ `WrightMap_multigroup.pdf` - ubicaciones de personas e ítems para for multigroup model
+ `WrightMap_anchored_Age2to4.pdf` - ubicaciones de personas e ítems para edades de 2 a 4 para el modelo anclado
+ `WrightMap_anchored_Age5to9.pdf` - ubicaciones de personas e ítems para edades de 5 a 9 para el modelo anclado
+ `WrightMap_anchored_Age10to17.pdf` - ubicaciones de personas e ítems para edades de 10 a 17 para el modelo anclado
* Ajuste de ítems:
+ `PCM2_itemfit_multigroup.xlsx` - ajuste de ítems para el modelo multigrupo
+ `PCM2_itemfit_anchored.xlsx` - ajuste de ítems para el modelo anclado
* Ajuste al modelo:
+ `PCM2_WLE_multigroup.txt` - fiabilidad del modelo multigrupo
+ `PCM2_WLE_anchored.txt` - fiabilidad del modelo anclado
# Argumentos de `rasch_mds_children()`
En esta sección examinaremos cada argumento de la función `rasch_mds_children()`. El archivo de ayuda para la función también describe los argumentos. Se puede acceder a los archivos de ayuda para las funciones en `R` escribiendo `?` antes del nombre de la función, de esta manera:
```{r rasch-mds-children-help}
?rasch_mds_children
```
A continuación se muestra un ejemplo de uso de la función `rasch_mds_children()`:
```{r rasch-mds-children-example}
rasch_mds_children(df = df_children,
vars_id = "HHID",
vars_group = "age_cat",
vars_metric_common = paste0("child", c(1:10)),
vars_metric_grouped = list(
"Age2to4" = paste0("child", c(12,15,16,19,20,24,25)),
"Age5to9" = paste0("child", c(11,13,14,17,18,20,21,22,23,24,25,27)),
"Age10to17" = paste0("child", c(11,13,14,17,18,20,21,22,23,25,26,27))),
TAM_model = "PCM2",
resp_opts = 1:5,
has_at_least_one = 4:5,
max_NA = 10,
print_results = TRUE,
path_parent = "~/Desktop/",
model_name = "Start",
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = "Initial run")
```
El primer argumento es `df`. Este argumento es para los datos. El objeto de datos debe ser datos de encuestas individuales, con una fila por persona. Aquí los datos se almacenan en un objeto `df_children`, que es un base de datos incluido en el paquete` whomds`. Para obtener más información sobre `df_children`, consulta su archivo de ayuda ejecutando:`?df_children`
El siguiente argumento es `vars_id`, que es el nombre de la columna utilizada para identificar de forma única a los individuos. Aquí la columna de ID se llama `HHID`.
El siguiente argumento es `vars_group`, que es una cadena con el nombre de la columna que identifica grupos, específicamente grupos de edad en este caso. Aquí la columna del grupo de edad es `age_cat`.
Los siguientes dos argumentos especifican las variables utilizadas para construir la métrica.
`vars_metric_common` es un vector de caracteres con los nombres de los ítems a los que cada individuo responde.
`vars_metric_grouped` es una lista nombrada de vectores de caracteres con los ítems a usar en el Análisis de Rasch por grupo de la variable especificada en `vars_group`. La lista debe tener nombres correspondientes a los diferentes grupos (por ejemplo, `Age2to4`,` Age5to9` y `Age10to17`), y contener vectores de caracteres de los elementos correspondientes para cada grupo.
Si solo se especifica `vars_metric_common`, entonces se realizará un análisis multigrupo. Si se especifican `vars_metric_common` y `vars_metric_grouped`, entonces se realizará un análisis anclado. `vars_metric_grouped` no se puede especificar por sí solo.
El siguiente argumento es `TAM_model`. Esta es una cadena que identifica qué modelo de IRT utilizar. Este valor se pasa a la función del paquete `TAM` utilizado para calcular el modelo de Rasch. El valor predeterminado es `"PCM2"`, que especifica el modelo de Rasch.
El siguiente argumento es `resp_opts`. Este es un vector numérico con las posibles opciones de respuesta para `vars_metric_common` y `vars_metric_grouped`. En esta encuesta, las preguntas `EF1` a `EF12` tienen las opciones de respuesta 1 a 5. Entonces, `resp_opts` es igual a un vector numérico de longitud 5 con los valores `1`, `2`,` 3`, `4` y `5`.
El siguiente argumento es `has_at_least_one`. Este es un vector numérico con las opciones de respuesta que un encuestado debe tener al menos una para ser incluido en el cálculo de la métrica. Este argumento es necesario porque a menudo el análisis de Rasch de los datos de los niños es más difícil debido a la extrema asimetría de las respuestas. Por esta razón, a menudo es aconsejable construir una escala solo con los encuestados en el extremo más grave del continuo de discapacidad, por ejemplo, solo con los encuestados que respondieron 4 o 5 a al menos una pregunta. Al especificar `has_at_least_one`, la función solo construirá una escala entre aquellos que respondieron `has_at_least_one` en al menos una pregunta de `vars_metric_common` y `vars_metric_grouped` El valor predeterminado es `4:5`, lo que significa que la escala se creará solo con hijos que respondieron 4 o 5 a al menos una pregunta en `vars_metric_common` y `vars_metric_grouped`. Los puntajes creados pueden reunirse con los niños excluidos post-hoc.
El siguiente argumento es `max_NA`. Este es un valor numérico para el número máximo de valores faltantes permitidos para que una persona aún se tenga en cuenta en el análisis. El Análisis de Rasch puede manejar a personas que tienen algunos valores faltantes, pero demasiados causarán problemas en el análisis. En general, todos los individuos en la muestra deben tener menos del 15% de valores faltantes. Aquí `max_NA` es `10`, lo que significa que se permite que los individuos tengan un máximo de dos valores faltantes de las preguntas en `vars_metric_common` y `vars_metric_grouped` para que aún se incluyan en el análisis.
El siguiente argumento es `print_results`, que es `TRUE` o `FALSE`. Cuando es `TRUE`, los archivos se guardarán en su computadora con los resultados de la iteración Rasch. Cuando es `FALSE`, los archivos no se guardarán.
El siguiente argumento es `path_parent`. Esta es una cadena con la ruta a la carpeta donde se guardarán los resultados de múltiples modelos, asumiendo que `print_results` es `TRUE`. La carpeta en `path_parent` contendrá carpetas separadas con los nombres especificados en `model_name` en cada iteración. En la ejecución de la función anterior, todos los resultados se guardarán en el Desktop. Ten en cuenta que al escribir rutas para `R`, todas las barras deberían ser: `/ `(NO `\`). Asegúrate de incluir un `/` final en el final de la ruta.
El siguiente argumento es `model_name`. Esto es igual a una cadena donde le das un nombre del modelo que estás ejecutando. Este nombre se usará como el nombre de la carpeta donde se guardará toda la salida en su computadora, si `print_results` es `TRUE`. El nombre que le des debe ser corto pero informativo. Por ejemplo, puede llamar a su primera ejecución "Start", como se llama aquí. Si creas un testlet en su segunda ejecución, quizás puedas llamarlo "Testlet1", etc. Elije lo que sea significativo para tí.
Los siguientes argumentos son `testlet_strategy`, `recode_strategy`, `drop_vars` y `split_strategy`. Estos son argumentos que controlan cómo se usan los datos en cada iteración del Modelo Rasch. Estos se especifican de la misma manera que en los modelos para adultos, como se describe en las secciones anteriores. Aquí están todos configurados en `NULL`, lo que significa que no se usan en la iteración del Análisis Rasch que se muestra aquí.
El último argumento es `comment`. Esto es igual a una cadena en la que puedes escribir cierta información de texto libre sobre la iteración actual para que cuando veas los resultados más adelante puedas recordar lo que hiciste y por qué lo hiciste. Es mejor ser más detallado, porque olvidarás por qué eligiste ejecutar el modelo de esta manera en particular. Este comentario se guardará en un archivo `Comment.txt`. Aquí el comentario es solo `"Initial run"`.
# Ejemplo
## Diferencias de modelos adultos
Ya hemos discutido las diferencias en el comando requerido para calcular el modelo de Rasch para niños. Para ejecutar este modelo, hay un paquete `R` diferente disponible: `TAM`. Este paquete puede ser más complicado de usar que `eRm` (el paquete utilizado para adultos), pero permite una mayor flexibilidad y, por lo tanto, nos permite calcular los análisis multigrupo y anclados que requerimos.
Con el paquete `TAM`, también podemos calcular diferentes tipos de modelos. Por defecto, el paquete `whomds` calcula los resultados utilizando el modelo de crédito parcial (el modelo de Rasch politomérico). El PCM se especifica en `TAM` con el argumento `TAM_model` igual a `"PCM2"`.
Otra opción para `TAM_model` es `"GPCM"`, que le dice al programa que calcule un Modelo de crédito parcial generalizado (GPCM). El GPCM se diferencia del PCM en que relaja el poder de discriminación uniforme de los artículos. Es decir, el GPCM permite que algunos ítems puedan identificar mejor las capacidades de las personas que otros ítems.
Nos enfocamos en PCM porque podemos obtener la escala que buscamos con este modelo.
## Mejorando la calidad del modelo
Como se mencionó anteriormente, en general, la distribución de las respuestas de los niños está mucho más inclinada hacia el final de la escala "sin discapacidad", por lo que es más difícil construir una métrica de calidad. **Su modelo mejorará enormemente si solo lo construye entre niños que indican tener algún tipo de nivel de problemas en al menos uno de los dominios.** Esta es la razón por la cual el valor predeterminado para el argumento `has_at_least_one` de `rasch_children()` es `4:5`. Recomendamos mantener este valor predeterminado.
Colapsando opciones de respuesta también puede mejorar la calidad de su escala. También recomendamos intentar construir una escala donde todos los ítems se recodifiquen a 0,1,1,2,2; en otras palabras, contraiga las opciones de respuesta 2a y 3a y las opciones de respuesta 3a y 4a.
## Salida importante para examinar
El resultado de las iteraciones del Modelo de Rasch para niños que utilizan los códigos de la OMS es muy similar al de los modelos para adultos. Sin embargo, para los modelos anclados (para Desempeño) en particular, para la mayoría de los tipos de archivos hay un archivo separado para cada grupo de edad. La calidad del modelo puede variar según los grupos de edad, y toda la información debe evaluarse simultáneamente para determinar cómo ajustar los datos.
Hay un par de diferencias clave que vamos a destacar. Para evaluar el ajuste del modelo (_targeting_) del modelo, abra el archivo `PCM2_WLE.txt` y analice el número después de `"WLE Reliability = "`. WLE significa "estimador de probabilidad ponderada" (en inglés _weighted likelihood estimator_), y corresponde al PSI que usamos para evaluar el ajuste del modelo para los modelos adultos. De manera similar, para un buen ajuste del modelo, nos gustaría ver que este número sea al menos mayor que 0.7, idealmente mayor que 0.8 o más.
El mapa persona-ítem también es diferente para el modelo de los niños. El paquete `TAM` utiliza otro paquete llamado` WrightMap` para producir _Wright Maps_. Estos son muy similares a los mapas de persona-ítem que utilizamos anteriormente, excepto que el tipo de umbrales que se muestran son diferentes. El _Wright Map_ muestra los "Umbrales Thurstonianos", y estos umbrales por definición nunca serán desordenados. Por lo tanto, es razonable no recodificar las opciones de respuesta para los niños, a menos que desee contraer las opciones de respuesta vacías o intentar mejorar la distribución de las ubicaciones de umbral para orientar mejor las capacidades de las personas.
Al igual que con los adultos, los nuevos puntajes reescalados para niños se encuentran en el archivo `Data_final.csv`.
# Mejores prácticas
Lea el vignette [Mejores prácticas con Análisis Rasch](c5_best_practices_ES.html) para aprender más sobre principios generales para usar.
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c4_rasch_children_ES.Rmd
|
---
title: "5 - Best practices with Rasch Analysis"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{5 - Best practices with Rasch Analysis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
Here we will discuss some general principles about how to implement the Rasch Model for your data.
* **It is easiest to run the model with a large sample and few items.** Samples of less than 200 people can be problematic, especially if there are a large number of items (20+) and responses to the items are not distributed evenly.
* In general, **minimal data adjustment is best**. Always try to see if you can make as few adjustments to your data as possible. This means the outcome of your analysis will better support your original survey instrument.
* **Try to make testlets only among items that are conceptually similar.** It is easier to justify combining items that are very similar (for instance, "feeling depressed" and "feeling anxious") than items that are extremely different (for instance, "walking 100m" and "remembering important things"). If you have high correlation among items that are very conceptually different, this may point to other problems with the survey instrument that should likely be addressed.
* When recoding, **try to collapse only adjacent thresholds** For instance, if you see that thresholds are disordered in the pattern 2, 1, 3, 4, it is natural to try to collapse thresholds 2 and 1 because they are adjacent. It would not make sense to collapse thresholds 2 and 4 because they are not adjacent.
* When recoding, **leave the first response option alone and do not recode it**. This first response option represents an answer in the MDS of "no problems" or "no difficulty", and it is best to leave this response option alone as a baseline. There is a larger conceptual difference between having "no problems" and "few problems" than there is between having "few problems" and "some problems", so it makes less sense to collapse the first two response options than it does to collapse the 2nd and 3rd response options.
* **It is normal to have to run many iterations of the model** in order to find a solution that works best, especially if you have many items in your instrument.
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c5_best_practices_EN.Rmd
|
---
title: "5 - Mejores prácticas con Análisis Rasch"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{5 - Mejores prácticas con Análisis Rasch}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>")
```
Aquí discutiremos algunos principios generales sobre cómo implementar el Modelo Rasch para tus datos.
* **Es más fácil ejecutar el modelo con una muestra grande y pocos ítems.** Las muestras de menos de 200 personas pueden ser problemáticas, especialmente si hay una gran cantidad de ítems (20+) y las respuestas a los ítems no son distribuido uniformemente
* En general, **el mínimo ajuste de datos es el mejor**. Siempre trata de ver si puedes hacer el mínimo ajuste posible a sus datos. Esto significa que el resultado de su análisis respaldará mejor su instrumento de encuesta original.
* **Trata de hacer testlets solo entre ítems que son conceptualmente similares.** Es más fácil justificar la combinación de ítems que son muy similares (por ejemplo, "sentirse deprimido" y "sentirse ansioso") que los ítems que son extremadamente diferentes (para ejemplo, "caminar 100m" y "recordar cosas importantes"). Si tienes una alta correlación entre los ítems que son muy diferentes conceptualmente, esto puede indicar otros problemas con el instrumento de la encuesta que probablemente deberían abordarse.
* Al recodificar, **intenta combinar solo umbrales adyacentes** Por ejemplo, si ves que los umbrales están desordenados en el patrón 2, 1, 3, 4, es natural tratar de contraer los umbrales 2 y 1 porque son adyacentes. No tendría sentido colapsar los umbrales 2 y 4 porque no son adyacentes.
* Al recodificar, **dejaa la primera opción de respuesta sola y no recodifícala**. Esta primera opción de respuesta representa una respuesta en el MDS de "no hay problemas" o "no hay dificultad", y es mejor dejar esta opción de respuesta sola como referencia. Hay una diferencia conceptual más grande entre "no tener problemas" y "pocos problemas" que entre tener "pocos problemas" y "algunos problemas", por lo que tiene menos sentido combinar las dos primeras opciones de respuesta que combinar las opciones de segunda y tercera respuesta.
* **Es normal tener que ejecutar muchas iteraciones del modelo** para encontrar una solución que funcione mejor, especialmente si tienes muchos ítems en su cuestionario.
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c5_best_practices_ES.Rmd
|
---
title: "6 - After Rasch Analysis: Descriptive Analysis"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{6 - After Rasch Analysis: Descriptive Analysis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
library(tidyr)
library(dplyr)
library(whomds)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>",
survey.lonely.psu = "adjust")
```
# Joining scores with original data
After you have finished with Rasch Analysis, the score is outputted in the file `Data_final.csv` in the column called `rescaled`. This file will only contain the individuals included in the analysis. Any individual who had too many missing values (`NA`) will not be in this file. It is often advisable to merge the original data with all individuals with the new scores. Any individual who did not have a score calculated will have an `NA` in this column.
This merge can be accomplished with the following code. First, open the library called `tidyverse` to access the necessary functions. Next, read in the `Data_final.csv` file and select only the columns you need: `ID` (or whatever the name of the individual ID column is in your data) and `rescaled`. The code below assumes that the file is in your working directory. You will have to include the full path to the file if it is not currently in your working directory. Finally, you can create an object `merged_data` that merges your original data, here represented with the object `original_data`, with the new score in a column renamed to `"DisabilityScore"` with the following code:
```{r join-example}
library(tidyverse)
new_score <- read_csv("Data_final.csv") %>%
select(c("ID", "rescaled"))
merged_data <- original_data %>%
left_join(new_score) %>%
rename("DisabilityScore" = "rescaled")
```
The sample data included in the `whomds` package called `df_adults` already has a Rasch score merged with it, in the column `disability_score`.
# Descriptive analysis
After calculating the disability scores using Rasch Analysis, you are now ready to analyze the results of the survey by calculating descriptive statistics. The `whomds` package contains functions to create tables and figures of descriptive statistics. This section will go over these functions.
## Tables
Descriptive statistics functions included in the `whomds` package are:
* `table_weightedpct()` - produces weighted tables of N or %
* `table_unweightedpctn()` - produces unweighted tables of N and %
* `table_basicstats()` - computes basic statistics of the number of members per group per household.
The arguments of each of these codes will be described below.
### `table_weightedpct()`
`whomds` contains a function called `table_weightedpct()` which calculates weighted results tables from the survey, disaggregated by specified variables. The arguments of this function are passed to functions in the package `dplyr`.
Below are the arguments of the function:
* `df` - the data frame with all the variables of interest
* `vars_ids` - variable names of the survey cluster ids
* `vars_strata` - variable names of the survey strata
* `vars_weights` - variable names of the weights
* `formula_vars` - vector of the column names of variables you would like to print results for
* `...` - captures expressions for filtering or transmuting the data. See the description of the argument `willfilter` below for more details
* `formula_vars_levels` - numeric vector of the factor levels of the variables in `formula_vars`. By default, the function assumes the variables have two levels: 0 and 1
* `by_vars` - the variables to disaggregate by
* `pct` - a logical variable indicating whether or not to calculate weighted percentages. Default is `TRUE` for weighted percentages. Set to `FALSE` for weighted N.
* `willfilter` - a variable that tells the function whether or not to filter the data by a particular value.
+ For example, if your `formula_vars` have response options of 0 and 1 but you only want to show the values for 1, then you would say `willfilter = TRUE`. Then at the end of your argument list you write an expression for the filter. In this case, you would say `resp==1`.
+ If you set `willfilter = FALSE`, then the function will assume you want to "transmute" the data, in other words manipulate the columns in some way, which for us often means to collapse response options. For example, if your `formula_vars` have 5 response options, but you only want to show results for the sum of options `"Agree"` and `"StronglyAgree"`, (after setting `spread_key="resp"` to spread the table by the response options) you could set `willfilter=FALSE`, and then directly after write the expression for the transmutation, giving it a new column name--in this case the expression would be `NewColName=Agree+AgreeStrongly`. Also write the names of the other columns you would like to keep in the final table.
+ If you leave `willfilter` as its default of `NULL`, then the function will not filter or transmute data.
* `add_totals` - a logical variable determining whether to create total rows or columns (as appropriate) that demonstrate the margin that sums to 100. Keep as the default `FALSE` to not include totals.
* `spread_key` - the variable to spread the table horizontally by. Keep as the default `NULL` to not spread the table horizontally.
* `spread_value` - the variable to fill the table with after a horizontal spread. By default this argument is `"prop"`, which is a value created internally by the function, and generally does not need to be changed.
* `arrange_vars` - the list of variables to arrange the table by. Keep as default `NULL` to leave the arrangement as is.
* `include_SE` - a logical variable indicating whether to include the standard errors in the table. Keep as the default `FALSE` to not include standard errors. As of this version of `whomds`, does not work when adding totals (`add_totals` is `TRUE`), spreading (`spread_key` is not `NULL`) or transmutting (`willfilter` is `FALSE`).
Here are some examples of how `table_weightedpct()` would be used in practice. Not all arguments are explicitly set in each example, which means they are kept as their default values.
#### Example 1: long table, one level of disaggregation
Let's say we want to print a table of the percentage of people in each disability level who gave each response option for a set of questions about the general environment. We would set the arguments of `table_weightedpct()` like this, and the first few rows of the table would look like this:
```{r table-weightedpct-example1, eval=TRUE}
#Remove NAs from column used for argument by_vars
df_adults_noNA <- df_adults %>%
filter(!is.na(disability_cat))
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = NULL,
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
```
The outputted table has 4 columns: the variable we disaggregated the data by (`disability_cat`, in other words the disability level), the item (`item`), the response option (`resp`), and the proportion (`prop`).
#### Example 2: wide table, one level of disaggregation
This long table from the above example is great for data analysis, but not great for reading with the bare eye. If we want to make it nicer, we convert it to "wide format" by "spreading" by a particular variable. Perhaps we want to spread by `disability_cat`. Our call to `table_weightedpct()` would now look like this, and the outputted table would be:
```{r table-weightedpct-example2, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
```
Now we can see our `prop` column has been spread horizontally for each level of `disability_cat`.
#### Example 3: wide table, one level of disaggregation, filtered
Perhaps, though, we are only interested in the proportions of the most extreme response option of 5. We could now add a filter to our call to `table_weightedpct()` like so:
```{r table-weightedpct-example3, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
```
Now you can see only the proportions for the response option of 5 are given.
#### Example 4: wide table, multiple levels of disaggregation, filtered
With `table_weightedpct()`, we can also add more levels of disaggregation by editing the argument `by_vars`. Here we will produce the same table as in Example 3 above but now disaggregated by disability level and sex:
```{r table-weightedpct-example4, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
```
#### Example 5: wide table, multiple levels of disaggregation, transmuted
Perhaps we are still interested not only in response option 5, but the sum of 4 and 5 together. We can do this by "transmuting" our table. To do this, we first choose to "spread" by `resp` by setting `spread_key="resp"`. This will convert the table to a wide format as in Example 2, but now each column will represent a response option. Then we set the transmutation by setting `willfilter=FALSE`, and adding expressions for the transmutation on the next line. We name all the columns we would like to keep and give an expression for how to create the new column of the sum of proportions for response options 4 and 5, here called `problems`:
```{r table-weightedpct-example5, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
)
```
If we would like to modify the table again so that `disability_cat` represents the columns again, we can feed this table into another function that will perform the pivot The function to pivot tables is called `pivot_wider()`, and it is in the `tidyr` package. To perform a second pivot, write the code like this:
```{r table-weightedpct-example5b, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
) %>%
pivot_wider(names_from = disability_cat, values_from = problems)
```
The `names_from` argument of the function `pivot_wider()` tells `R` which variable to use as the columns, and `values_from` tells `R` what to fill the columns with. The operator `%>%` is commonly referred to as a "pipe". It feeds the object before it into the first argument of the function after it. For example, if you have an object `x` and a function `f`, writing `x %>% f()` would be the equivalent as writing `f(x)`. People use "pipes" because they make long sequences of code easier to read.
### `table_unweightedpctn()`
`whomds` contains a function called `table_unweightedpctn()` that produces unweighted tables of N and %. This is generally used for demographic tables. Its arguments are as follows:
* `df` - the data frame with all the variables of interest
* `vars_demo` - vector with the names of the demographic variables for which the N and % will be calculated
* `group_by_var` - name of the variable in which the statistics should be stratified (e.g. `"disability_cat"`)
* `spread_by_group_by_var` - logical determining whether to spread the table by the variable given in `group_by_var`. Default is `FALSE`.
* `group_by_var_sums_to_100` - logical determining whether percentages sum to 100 along the margin of `group_by_var`, if applicable. Default is `FALSE`.
* `add_totals` - a logical variable determining whether to create total rows or columns (as appropriate) that demonstrate the margin that sums to 100. Keep as the default `FALSE` to not include totals.
Here is an example of how it is used:
```{r table-unweightedpctn-example, eval=TRUE}
table_unweightedpctn(df_adults_noNA,
vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"),
group_by_var = "disability_cat",
spread_by_group_by_var = TRUE)
```
### `table_basicstats()`
The function `table_basicstats()` computes basic statistics of the number of member per group per household. Its arguments are:
* `df` - a data frame of household data where the rows represent members of the households in the sample
* `hh_id` - string (length 1) indicating the name of the variable in `df` uniquely identifying households
* `group_by_var` - string (length 1) with name of variable in `df` to group results by
Here is an example of how it is used:
```{r table-basicstats-example, eval=TRUE}
table_basicstats(df_adults_noNA, "HHID", "age_cat")
```
## Figures
Descriptive statistics figure functions included in the `whomds` package are:
* `fig_poppyramid()` - produces a population pyramid figure for the sample
* `fig_dist()` - produces a plot of the distribution of a score
* `fig_density()` - produces a plot of the density of a score
The arguments of each of these codes will be described below.
### `fig_poppyramid()`
`whomds` contains a function called `fig_poppyramid()` that produces a population pyramid figure for the sample. This function takes as arguments:
* `df` - the data where each row is a member of the household from the household roster
* `var_age` - the name of the column in `df` with the persons' ages
* `var_sex` - the name of the column in `df` with he persons' sexes
* `x_axis` - a string indicating whether to use absolute numbers or sample percentage on the x-axis. Choices are `"n"` (default) or `"pct"`.
* `age_plus` - a numeric value indicating the age that is the first value of the oldest age group. Default is 100, for the last age group to be 100+
* `age_by` - a numeric value indicating the width of each age group, in years. Default is 5.
Running this function produces a figure like the one below:
```{r plot-pop-pyramid, eval=TRUE, echo=FALSE}
include_graphics("Images/pop_pyramid.png")
```
### `fig_dist()`
`whomds` contains a function called `fig_dist()` that produces a plot of the distribution of a score. WHO uses this function to show the distribution of the disability scores calculated with Rasch Analysis. Its arguments are:
* `df` - data frame with the score of interest
* `score` - character variable of score variable name ranging from 0 to 100; ex. `"disability_score"`
* `score_cat` - character variable of score categorization variable name, ex. `"disability_cat"`
* `cutoffs` - a numeric vector of the cut-offs for the score categorization
* `x_lab` - a string giving the x-axis label. Default is `"Score"`
* `y_max` - maximum value to use on the y-axis. If left as the default `NULL`, the function will calculate a suitable maximum automatically.
* `pcent` - logical variable indicating whether to use percent on the y-axis or frequency. Leave as default `FALSE` for frequency and give `TRUE` for percent.
* `pal` - a string specifying the type of color palette to use, passed to the function `RColorBrewer::brewer.pal()`. Default is `"Blues"`.
* `binwidth` - a numeric value giving the width of the bins in the histograph. Default is 5.
Running this function produces a figure like the one below.
```{r plot-distribution, eval=TRUE, echo=FALSE}
include_graphics("Images/distribution.png")
```
### `fig_density()`
`whomds` contains a function similar to `fig_dist()` called `fig_density()` that produces a plot of the density of a score. WHO uses this function to show the density distribution of the disability scores calculated with Rasch Analysis. Its arguments are:
* `df` - data frame with the score of interest
* `score` - character variable of score variable name ranging from 0 to 100; ex. `"disability_score"`
* `var_color` - a character variable of the column name to set color of density lines by. Use this variable if you could like to print the densities of different groups onto the same plot. Default is `NULL`.
* `var_facet` - a character variable of the column name for the variable to create a `ggplot2::facet_grid()` with, which will plot densities of different groups in side-by-side plots. Default is `NULL`.
* `cutoffs` - a numeric vector of the cut-offs for the score categorization
* `x_lab` - a string giving the x-axis label. Default is `"Score"`
* `pal` - a string specifying either a manual color to use for the color aesthetic, a character vector explictly specifying the colors to use for the color scale, or as the name of a palette to pass to `RColorBrewer::brewer.pal() ` with the name of the color palette to use for the color scale. Default is `"Paired"`
* `adjust` - a numeric value to pass to `adjust` argument of `ggplot2::geom_density()`, which controls smoothing of the density function. Default is 2.
* `size` - a numeric value to pass to `size` argument of `ggplot2::geom_density()`, which controls the thickness of the lines. Default is 1.5.
Running this function produces a figure like the one below.
```{r plot-density, eval=TRUE, echo=FALSE}
include_graphics("Images/density.png")
```
## Descriptive statistics templates
WHO also provides a template for calculating many descriptive statistics tables for use in survey reports, also written in `R`. If you would like a template for your country, please contact us (see DESCRIPTION for contact info).
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c6_after_rasch_EN.Rmd
|
---
title: "6 - Después de Análisis Rasch: Análisis descriptivo"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{6 - Después de Análisis Rasch: Análisis descriptivo}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
library(knitr)
library(tidyr)
library(dplyr)
library(whomds)
opts_chunk$set(warning=FALSE,
message=FALSE,
eval=FALSE,
out.width = "80%",
fig.align = "center",
collapse = TRUE,
comment = "#>",
survey.lonely.psu = "adjust")
```
# Unir puntajes con datos originales
Una vez que haya terminado con Rasch Analysis, la puntuación se genera en el archivo `Data_final.csv` en la columna llamada `rescaled`. Este archivo solo contendrá los individuos incluidos en el análisis. Cualquier persona que tenga demasiados valores perdidos (`NA`) no estará en este archivo. A menudo es recomendable combinar los datos originales con todos los individuos con las nuevas puntuaciones. Cualquier persona que no haya calculado una puntuación tendrá un `NA` en esta columna.
Esta unión se puede lograr con el siguiente código. Primero, abre el paquete llamada `tidyverse` para acceder a las funciones necesarias. A continuación, lee el archivo `Data_final.csv` y selecciona solo las columnas que necesitas: `ID` (o cualquiera que sea el nombre de la columna de identificación individual en sus datos) y `rescaled`. El siguiente código asume que el archivo está en su directorio operativo. Tendrás que incluir la ruta completa al archivo si no está actualmente en su directorio operativo. Finalmente, puedes crear un objeto `merged_data` que fusione sus datos originales, aquí representados con el objeto `original_data`, con la nueva puntuación en una columna renombrada a `"DisabilityScore"` con el siguiente código:
```{r join-example}
library(tidyverse)
new_score <- read_csv("Data_final.csv") %>%
select(c("ID", "rescaled"))
merged_data <- original_data %>%
left_join(new_score) %>%
rename("DisabilityScore" = "rescaled")
```
Los datos de ejemplo incluidos en el paquete `whomds` llamado `df_adults` ya tienen una puntuación de Rasch combinada, en la columna `disability_score`.
# Después de Rasch: análisis descriptivo
Después de calcular los puntajes de discapacidad con el Análisis Rasch, ahora estás listo para analizar los resultados de la encuesta mediante el cálculo de estadísticas descriptivas. El paquete `whomds` contiene funciones para crear tablas y figuras de estadísticas descriptivas. Esta sección repasará estas funciones.
## Tablas
Las funciones de estadísticas descriptivas incluidas en el paquete `whomds` son:
* `table_weightedpct()` - produce tablas ponderadas de N o %
* `table_unweightedpctn()` - produce tablas no ponderadas de N y %
* `table_basicstats()` - calcula estadísticas básicas del número de miembros por grupo por hogar.
Los argumentos de cada uno de estos códigos se describirán a continuación.
### `table_weightedpct()`
`whomds` contiene una función llamada `table_weightedpct ()` que calcula las tablas de resultados ponderados de la encuesta, desagregadas por variables especificadas. Los argumentos de esta función se pasan a funciones en el paquete `dplyr`.
A continuación se presentan los argumentos de la función:
* `df` - el marco de datos con todas las variables de interés
* `vars_ids` - nombres de variables de los identificadores de cluster de encuesta
* `vars_strata` - nombres de variables de los estratos de la encuesta
* `vars_weights` - nombres de variables de los ponderaciones
* `formula_vars` - vector de los nombres de columna de las variables para las que desea imprimir los resultados
* `...` - captura expresiones para filtrar o transmutar los datos. Vee la descripción del argumento `willfilter` a continuación para más detalles.
* `formula_vars_levels` - vector numérico de los niveles de factor de las variables en `formula_vars`. Por defecto, la función asume que las variables tienen dos niveles: 0 y 1
* `by_vars` - las variables por las que desagregas
* `pct` - una variable lógica que indica si se deben calcular o no los porcentajes ponderados. El valor predeterminado es `TRUE` para porcentajes ponderados. Ajuste a `FALSE` para N ponderada
* `willfilter` - una variable que le dice a la función si filtrarás o no los datos por un valor particular.
+ Por ejemplo, si sus `formula_vars` tienen opciones de respuesta de 0 y 1 pero solo quieres mostrar los valores para 1, entonces diría que `willfilter = TRUE`. Luego, al final de la lista de argumentos, escribe una expresión para el filtro. En este caso, dirías `resp == 1`.
+ Si es `willfilter = FALSE`, entonces la función asumirá que desea "transmutar" los datos, en otras palabras, manipular las columnas de alguna manera, lo que para nosotros a menudo significa combinar las opciones de respuesta. Por ejemplo, si sus `formula_vars` tienen 5 opciones de respuesta, pero solo desea mostrar los resultados para la suma de las opciones `"Agree"` y `"StronglyAgree"`, (después de configurar `spread_key = "resp"` para extender el tabla por las opciones de respuesta) podrías escribir `willfilter = FALSE`, y luego directamente después de escribir la expresión para la transmutación, dándole un nuevo nombre de columna; en este caso, la expresión sería` NewColName = Agree + AgreeStrongly`. También escribe los nombres de las otras columnas que te gustaría mantener en la tabla final.
+ Si deja `willfilter` como su valor predeterminado de `NULL`, la función no filtrará ni transmutará los datos.
* `add_totals`: una variable lógica que determina si se crean filas o columnas totales (según corresponda) que demuestren el margen que suma a 100. Manténlo como el valor predeterminado `FALSE` para no incluir los totales.
* `spread_key` - la variable para la que extiendas la tabla horizontalmente. Mantén como predeterminado `NULL` para no extender la tabla horizontalmente.
* `spread_value` - la variable con la que se llena la tabla después de una extensión horizontal. Por defecto, este argumento es `"prop"`, que es un valor creado internamente por la función y generalmente no necesita ser cambiado.
* `arrange_vars` - la lista de variables para la que organizas la tabla. Mantén como predeterminado `NULL` para dejar el arreglo como está.
* `include_SE` - una variable lógica que indica si se deben incluir los errores estándar en la tabla. Mantén como predeterminado `FALSE` para no incluir errores estándar. A partir de esta versión de `whomds`, no funciona si incluyes totales (`add_totals` es `TRUE`), extensión (`spread_key` no es `NULL`) o transmutación (`willfilter` es `FALSE`).
Aquí hay algunos ejemplos de cómo se usaría `table_weightedpct()` en la práctica. No todos los argumentos se establecen explícitamente en cada ejemplo, lo que significa que se mantienen como sus valores predeterminados.
#### Ejemplo 1: tabla larga, un nivel de desagregación
Digamos que queremos imprimir una tabla del porcentaje de personas en cada nivel de discapacidad que dieron cada opción de respuesta para un conjunto de preguntas sobre el entorno general. Escribiríamos los argumentos de `table_weightedpct()` de esta manera, y las primeras filas de la tabla se verían así:
```{r table-weightedpct-example1, eval=TRUE}
#Quitar NAs de la columna utilizada para el argumento by_vars
df_adults_noNA <- df_adults %>%
filter(!is.na(disability_cat))
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = NULL,
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
```
La tabla de resultados tiene 4 columnas: la variable por la que desagregamos los datos (`disability_cat`, es decir, el nivel de discapacidad), el elemento (`item`), la opción de respuesta (`resp`) y la proporción (`prop`).
#### Ejemplo 2: tabla ancha, un nivel de desagregación
Esta larga tabla del ejemplo anterior es excelente para el análisis de datos, pero no excelente para leer a simple vista. Si queremos hacerlo más bonito, lo convertimos a "formato ancho" mediante "extensión" mediante una variable particular. Tal vez queremos extender por `disability_cat`. Nuestra ejecución de `table_weightedpct()` ahora se vería así, y la tabla de salida sería:
```{r table-weightedpct-example2, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = NULL
)
```
Ahora podemos ver que nuestra columna `prop` se ha extendido horizontalmente para cada nivel de` disability_cat`.
#### Ejemplo 3: tabla amplia, un nivel de desagregación, filtrado
Quizás, sin embargo, solo nos interesan las proporciones de la opción de respuesta más extrema de 5. Ahora podríamos agregar un filtro a nuestra ejecución a `table_weightedpct()` así:
```{r table-weightedpct-example3, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = "disability_cat",
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
```
Ahora puede ver que solo se dan las proporciones para la opción de respuesta de 5.
#### Ejemplo 4: tabla ancha, múltiples niveles de desagregación, filtrada
Con `table_weightedpct()`, también podemos agregar más niveles de desagregación editando el argumento `by_vars`. Aquí produciremos la misma tabla que en el Ejemplo 3 anterior, pero ahora desagregada por nivel de discapacidad y sexo:
```{r table-weightedpct-example4, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "disability_cat",
spread_value = "prop",
arrange_vars = NULL,
willfilter = TRUE,
resp == 5
)
```
#### Ejemplo 5: tabla ancha, niveles múltiples de desagregación, transmutada
Quizás todavía estamos interesados no solo en la opción de respuesta 5, sino en la suma de 4 y 5 juntos. Podemos hacer esto "transmutando" nuestra tabla. Para hacer esto, primero elegimos "extender" por `resp` configurando `spread_key = "resp"`. Esto convertirá la tabla a un formato ancho como en el Ejemplo 2, pero ahora cada columna representará una opción de respuesta. Luego configuramos la transmutación estableciendo `willfilter = FALSE`, y agregando expresiones para la transmutación en la siguiente línea. Nombramos todas las columnas que nos gustaría mantener y damos una expresión de cómo crear la nueva columna de la suma de proporciones para las opciones de respuesta 4 y 5, aquí llamada "problemas":
```{r table-weightedpct-example5, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
)
```
Si nos gustaría modificar la tabla nuevamente para que `disability_cat` represente las columnas nuevamente, podemos incluir esta tabla en otra función que realizará el "pivot". La función para extender tablas se llama `pivot_wider()`, y está en el paquete `tidyr`. Para realizar una segunda extensión, escribe el código así:
```{r table-weightedpct-example5b, eval=TRUE}
table_weightedpct(
df = df_adults_noNA,
vars_ids = "PSU",
vars_strata = "strata",
vars_weights = "weight",
formula_vars = paste0("EF", 1:12),
formula_vars_levels = 1:5,
by_vars = c("disability_cat", "sex"),
spread_key = "resp",
spread_value = "prop",
arrange_vars = NULL,
willfilter = FALSE,
disability_cat, sex, item, problems = `4`+`5`
) %>%
pivot_wider(names_from = disability_cat, values_from = problems)
```
El argumento `names_from` de la función `pivot_wider()` le dice a `R` qué variable usar como columnas, y `values_from` le dice a` R` con qué llenar las columnas. El operador `%>%` se conoce comúnmente como una _"pipe"_. Pone el objeto anterior en el primer argumento de la función posterior. Por ejemplo, si tiene un objeto `x` y una función `f`, escribir `x %>% f ()` sería el equivalente a escribir `f(x)`. Las personas usan _"pipes"_ porque hacen que las secuencias largas de código sean más fáciles de leer.
### `table_unweightedpctn()`
`whomds` contiene una función llamada `table_unweightedpctn()` que produce tablas no ponderadas de N y %. Esto se utiliza generalmente para tablas demográficas. Sus argumentos son los siguientes:
* `df` - el marco de datos con todas las variables de interés
* `vars_demo` - vector con los nombres de las variables demográficas para las que se calcularán N y %
* `group_by_var`: nombre de la variable en la que se deben estratificar las estadísticas (por ejemplo, `"disability_cat"`)
* `spread_by_group_by_var` - determina lógicamente si se debe extender la tabla mediante la variable dada en `group_by_var`. El valor predeterminado es `FALSE`.
* `group_by_var_sums_to_100` - determina lógicamente si los porcentajes suman 100 en el margen de `group_by_var`, si corresponde. El valor predeterminado es `FALSE`.
* `add_totals`: una variable lógica que determina si se crean filas o columnas totales (según corresponda) que demuestren el margen que suma 100. Manténlo como el valor predeterminado `FALSE` para no incluir los totales.
Aquí hay un ejemplo de cómo se usa:
```{r table-unweightedpctn-example, eval=TRUE}
table_unweightedpctn(df_adults_noNA,
vars_demo = c("sex", "age_cat", "work_cat", "edu_cat"),
group_by_var = "disability_cat",
spread_by_group_by_var = TRUE)
```
### `table_basicstats()`
La función `table_basicstats()` calcula estadísticas básicas del número de miembros por grupo por hogar. Sus argumentos son:
* `df` - un marco de datos de datos de hogares donde las filas representan miembros de los hogares en la muestra
* `hh_id` - cadena (longitud 1) que indica el nombre de la variable en `df` que identifica hogares únicamente
* `group_by_var` - cadena (longitud 1) con el nombre de la variable en `df` para la que se agrupa los resultados
Aquí hay un ejemplo de cómo se usa:
```{r table-basicstats-example, eval=TRUE}
table_basicstats(df_adults_noNA, "HHID", "age_cat")
```
## Figuras
Las funciones de las estadísticas descriptivas incluidas en el paquete `whomds` son:
* `fig_poppyramid()` - produce una figura de pirámide de población para la muestra
* `fig_dist()` - produce un gráfico de la distribución de una puntuación
* `fig_density()` - produce un gráfico de la densidad de una puntación
Los argumentos de cada uno de estos códigos se describirán a continuación.
### `fig_poppyramid()`
`whomds` contiene una función llamada `fig_poppyramid()` que produce una figura de pirámide de población para la muestra. Esta función toma como argumentos:
* `df` - los datos donde cada fila es un miembro del hogar de la lista del hogar
* `var_age` - el nombre de la columna en `df` con las edades de las personas
* `var_sex` - el nombre de la columna en `df` con los sexos de las personas
* `x_axis` - una cadena que indica si se deben usar números absolutos o porcentaje de muestra en el eje horizontal. Las opciones son `"n"` (predeterminado) o `"pct"`.
* `age_plus` - un valor numérico que indica la edad que es el primer valor del grupo de edad más antiguo. El valor predeterminado es 100, para el último grupo de edad de 100 o más.
* `age_by` - un valor numérico que indica el ancho de cada grupo de edad, en años. El valor predeterminado es 5.
Ejecutar esta función produce una figura como la siguiente:
```{r plot-pop-pyramid, eval=TRUE, echo=FALSE}
include_graphics("Images/pop_pyramid.png")
```
### `fig_dist()`
`whomds` contiene una función llamada `fig_dist()` que produce un gráfico de la distribución de una puntuación. La OMS utiliza esta función para mostrar la distribución de las puntuaciones de discapacidad calculadas con el Análisis de Rasch. Sus argumentos son:
* `df` - marco de datos con la puntuación de interés
* `score` - variable de carácter del nombre de variable de puntuación que va de 0 a 100; ej. `"disability_score"`
* `score_cat` - variable de carácter del nombre de variable de categorización de puntuación, ej. `"disability_cat"`
* `cutoffs` - un vector numérico de los puntos de corte para la categorización de puntuación
* `x_lab` - una cadena que da la etiqueta del eje horizontal. El valor predeterminado es `"Score"`
* `y_max` - valor máximo para usar en el eje vertical. Si se deja como predeterminado `NULL`, la función calculará un máximo adecuado automaticamente.
* `pcent` - variable lógica que indica si se debe usar el porcentaje en el eje y o la frecuencia. Deje por defecto `FALSE` para la frecuencia y dé `TRUE` para el porcentaje.
* `pal` - una cadena que especifica el tipo de paleta de colores a usar, que se pasa a la función `RColorBrewer::brewer.pal()`. El valor predeterminado es `"Blues"`.
* `binwidth` - un valor numérico que da el ancho de los contenedores en el histógrafo. El valor predeterminado es 5.
Ejecutar esta función produce una figura como la de abajo.
```{r plot-distribution, eval=TRUE, echo=FALSE}
include_graphics("Images/distribution.png")
```
### `fig_density()`
`whomds` contiene una función similar a `fig_dist()` llamada `fig_density()` que produce un gráfico de la densidad de una puntuación. La OMS utiliza esta función para mostrar la distribución de densidad de las puntuaciones de discapacidad calculadas con el Análisis de Rasch. Sus argumentos son:
* `df` - marco de datos con la puntuación de interés
* `score` - variable de carácter del nombre de variable de puntuación que va de 0 a 100; ej. `"disability_score"`
* `var_color` - variable de carácter con el nombre de la columna que se usa para determinar los colores de las líneas de densidad. Se usa este variable para imprimir las densidades de diferentes groups en el mismo gráfico. El valor predeterminado es `NULL`.
* `var_facet` - variable de carácter con el nombre de la columna que se usa para crear un gráfico con `ggplot2::facet_grid()`, que se imprime las densidades de diferentes groups lado a lado. El valor predeterminado es `NULL`.
* `cutoffs` - un vector numérico de los puntos de corte para la categorización de puntuación
* `x_lab` - una cadena que da la etiqueta del eje horizontal. El valor predeterminado es `"Score"`
* `pal` - una cadena que especifica un color manual para utilizar para el aestitico del color, un vector de carácter que especifica los colores que se usa para la escala de colores, o como el tipo de paleta de colores a usar para la escala de colores, que se pasa a la función `RColorBrewer::brewer.pal()`. El valor predeterminado es `"Paired"`
* `adjust` - un valor numérico que se pasa al argumento `adjust` de `ggplot2::geom_density()`, que suaviza la función de la densidad. El valor predeterminado es 2.
* `size` - un valor numérico que se pasa al argumento `size` de `ggplot2::geom_density()`, que controla el espesor de las líneas. El valor predeterminado es 1.5.
Ejecutar esta función produce una figura como la de abajo.
```{r plot-density, eval=TRUE, echo=FALSE}
include_graphics("Images/density.png")
```
## Plantillas para estadísticas descriptivas
La OMS también proporciona una plantilla para calcular muchas tablas de estadísticas descriptivas para su uso en informes de encuestas, también escritas en `R`. Si desea una plantilla para su país, contáctenos (por favor abre el archivo DESCRIPTION para obtender los detalles de contacto).
|
/scratch/gouwar.j/cran-all/cranData/whomds/vignettes/c6_after_rasch_ES.Rmd
|
H.Earth.solar <-
function(x, y, dateDate) { ######################
Hst.ls <- list()
n <- length(y)
tau <- length(dateDate)
equinox <- strptime( "20110320", "%Y%m%d" )
for(i in 1:tau) {
this.date <- dateDate[i]
dfe <- as.integer( difftime(this.date, equinox, units="day")) ; dfe
psi <- 23.5 * sin( 2*pi*dfe/365.25 ) ; psi
eta <- 90 - (360/(2*pi)) * acos( cos(2*pi*y/360) * cos(2*pi*psi/360) + sin(2*pi*y/360) * sin(2*pi*psi/360) )
surface.area <- sin(2*pi*eta/360) ; surface.area
# surface.area[ surface.area < 0 ] <- 0
Hst.ls[[i]] <- cbind( surface.area )
}
return(Hst.ls)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/H.Earth.solar.R
|
H.als.b <-
function(Z, Hs, Ht, Hst.ls, rho, reg, b.lag=-1, Hs0=NULL, Ht0=NULL, Hst0.ls=NULL) {
tau <- nrow(Z)
n <- ncol(Z)
Z.als <- matrix(NA, tau, n)
if( is.null( Hs ) ) { use.Hs <- FALSE ; d.s <- 0 } else { use.Hs <- TRUE ; d.s <- ncol( Hs ) }
if( is.null( Ht ) ) { use.Ht <- FALSE ; d.t <- 0 } else { use.Ht <- TRUE ; d.t <- ncol( Ht ) }
if( is.null( Hst.ls ) ) { use.Hst.ls <- FALSE ; d.st <- 0 } else { use.Hst.ls <- TRUE ; d.st <- ncol( Hst.ls[[1]] ) }
d <- d.s + d.t + d.st
B <- matrix(0, tau, d)
reg.mx <- diag( reg, d )
LHH <- 0
LHy <- 0
g <- 1
use.H0 <- !is.null(Hs0) | !is.null(Ht0) | !is.null(Hst0.ls)
if( use.H0 ) {
if( !is.null(Hs0) ) { n0 <- nrow(Hs0) ; Z.als.0 <- matrix(NA, tau, n0) } else { n0 <- nrow(Hst0.ls[[1]]) }
}
low.ndx <- max( 1, 1-b.lag )
top.ndx <- min( tau, tau-b.lag )
for(i in low.ndx:top.ndx) {
if( use.Ht ) { this.Ht.mx <- matrix( Ht[ i, ], n, d.t, byrow=TRUE ) } else { this.Ht.mx <- NULL }
this.H <- cbind( Hs, this.Ht.mx, Hst.ls[[i]] )
if( use.H0 ) {
if( use.Ht ) { this.Ht0.mx <- matrix( Ht0[ i, ], n0, d.t, byrow=TRUE ) } else { this.Ht0.mx <- NULL }
this.H0 <- cbind( Hs0, this.Ht0.mx, Hst0.ls[[i]] )
}
this.HH <- crossprod(this.H)
this.Hy <- crossprod(this.H, Z[ i, ])
LHH <- LHH + g * ( this.HH - LHH )
LHy <- LHy + g * ( this.Hy - LHy )
inv.LHH <- try( solve( LHH + reg.mx ), silent=TRUE )
## if( class(inv.LHH) != "try=error" ) { inv.LHH <- inv.LHH } else { inv.LHH <- matrix(0, d, d) }
if( is(inv.LHH, "try-error") ) { inv.LHH <- matrix(0, d, d) }
B[ i, ] <- inv.LHH %*% LHy
Z.als[ i, ] <- B[ i + b.lag, ] %*% t(this.H)
if( use.H0 ) { Z.als.0[ i, ] <- B[ i + b.lag, ] %*% t(this.H0) } else { Z.als.0 <- NULL }
g <- (g+rho) / (g+rho+1)
}
return( list("Z.hat"=Z.als, "B"=B, "Z0.hat"=Z.als.0, "inv.LHH"=inv.LHH, "ALS.g"=g) )
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/H.als.b.R
|
Hals.fastcv.snow <-
function(j, rm.ndx, Z, Hs, Ht, Hst.ls, GP.mx) {
n <- ncol(Z)
tau <- nrow(Z)
rho <- GP.mx[j, 1]
reg <- GP.mx[j, 2]
Z.hat <- matrix(NA, tau, n)
for( drop.ndx in rm.ndx ) {
if( !is.null(Hst.ls) ) {
red.Hst.ls <- list()
Hst0.ls <- list()
for(i in 1:tau) {
red.Hst.ls[[i]] <- Hst.ls[[i]][ -drop.ndx, , drop=FALSE]
Hst0.ls[[i]] <- Hst.ls[[i]][ drop.ndx, , drop=FALSE]
}
} else {
red.Hst.ls <- NULL
Hst0.ls <- NULL
}
if( !is.null(Hs) ) {
red.Hs <- Hs[ -drop.ndx, , drop=FALSE]
Hs0 <- Hs[ drop.ndx, , drop=FALSE]
} else {
red.Hs <- NULL
Hs0 <- NULL
}
Z.hat[ ,drop.ndx] <- H.als.b(Z[ , -drop.ndx, drop=FALSE], Hs=red.Hs, Ht=Ht, Hst.ls=red.Hst.ls, rho, reg, b.lag=0, Hs0=Hs0, Ht0=Ht, Hst0.ls=Hst0.ls)$Z0.hat
}
return(Z.hat)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/Hals.fastcv.snow.R
|
Hals.ses <-
function(Z, Hs, Ht, Hst.ls, rho, reg, b.lag, test.rng) {
tau <- tau
xALS <- H.als.b(Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, rho=rho, reg=reg, b.lag=b.lag, Hs0=NULL, Ht0=NULL, Hst0.ls=NULL)
rmse <- sqrt( mean( ( Z[ test.rng, ] - xALS$Z.hat[ test.rng, ] )^2 ) ) ; rmse
als.se <- rmse * sqrt( xALS$ALS.g ) * sqrt( diag( xALS$inv.LHH ) )
return( list( "estimates"=cbind( xALS$B[ tau, ], als.se ), "inv.LHH"=xALS$inv.LHH, "ALS.g"=xALS$ALS.g ) )
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/Hals.ses.R
|
Hals.snow <-
function(j, Z, Hs, Ht, Hst.ls, b.lag, GP.mx) {
rho <- GP.mx[j, 1]
reg <- GP.mx[j, 2]
Z.hat <- H.als.b(Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, rho=rho, reg=reg, b.lag=b.lag, Hs0=NULL, Ht0=NULL, Hst0.ls=NULL)$Z.hat
return(Z.hat)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/Hals.snow.R
|
Hst.sumup <-
function(Hst.ls, Hs=NULL, Ht=NULL) {
tau <- length(Hst.ls)
n <- nrow(Hst.ls[[1]])
big.sum <- 0
for(i in 1:tau) {
if( !is.null(Ht) ) { Ht.mx <- matrix( Ht[i, ], n, ncol(Ht), byrow=TRUE ) } else { Ht.mx <- NULL }
big.sum <- big.sum + crossprod( cbind( Hs, Ht.mx, Hst.ls[[i]] ) )
}
return( big.sum )
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/Hst.sumup.R
|
MSS.snow <-
function (FUN.source, current.best, p.ndx.ls, f.d, sds.mx, k.glob, k.loc.coef, X = NULL) {
run.parallel <- run.parallel
sfClusterApplyLB <- sfClusterApplyLB
envmh <- environment(NULL)
GP <- GP
if(is.function(FUN.source)) {
FUN.source()
} else {
if (!is.null(FUN.source)) {
source(FUN.source)
}
}
FUN.GP <- FUN.GP
FUN.MH <- FUN.MH
FUN.I <- FUN.I
FUN.EXIT <- FUN.EXIT
if (is.na(current.best)) {
GP.mx <- matrix(GP, 1, length(GP))
if (!is.null(FUN.GP)) {
GP.mx <- FUN.GP(GP.mx)
}
current.best <- FUN.MH(1, GP.mx = GP.mx, X = X)
cat(current.best, "\n")
}
if (!is.null(k.glob)) {
for (k.times in 1:k.glob) {
cat(k.times, "\n")
for (p.ndx in p.ndx.ls) {
n.mh <- as.integer(k.loc.coef * 2^length(p.ndx))
GP.mx <- matrix(GP, n.mh, length(GP), byrow = TRUE)
for (ip in p.ndx) {
GP.mx[, ip] <- f.d[[ip]](n.mh, GP[ip], sds.mx[k.times,
ip])
}
if (!is.null(FUN.GP)) {
GP.mx <- FUN.GP(GP.mx)
}
if (run.parallel) {
sfOut <- sfClusterApplyLB(1:n.mh, FUN.MH, GP.mx = GP.mx,
X = X)
} else {
sfOut <- list()
for (jj in 1:n.mh) {
sfOut[[jj]] <- FUN.MH(jj, GP.mx = GP.mx,
X = X)
}
}
errs <- unlist(sfOut)
errs[is.na(errs)] <- Inf
errs[is.nan(errs)] <- Inf
best.ndx <- which(errs == min(errs))[1]
if (errs[best.ndx] < current.best) {
current.best <- errs[best.ndx]
GP <- GP.mx[best.ndx, , drop = TRUE]
#assign("current.best", current.best, envir = envmh)
#assign("current.best.GP", GP, envir = envmh)
current.best <<- current.best
current.best.GP <- GP
current.best.GP <<- current.best.GP
X <- FUN.I(envmh = envmh, X = X)
}
}
}
}
if (!is.null(FUN.EXIT)) {
FUN.EXIT(envmh = envmh, X = X)
}
#assign("GP", GP, pos = globalenv())
GP <<- GP
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/MSS.snow.R
|
Z.clean.up <-
function(Z) {
Z[ Z == Inf | Z == -Inf ] <- NA
Z[ is.na(Z) | is.nan(Z) ] <- mean(Z, na.rm=TRUE)
return(Z)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/Z.clean.up.R
|
applystnd.Hs <-
function( Hs0, x ) {
sHs0 <- t( ( t(Hs0) - x$h.mean ) / x$h.sd )
if( x$intercept ) { sHs0[ , 1] <- 1 / sqrt(x$n) }
return(sHs0)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/applystnd.Hs.R
|
applystnd.Hst.ls <-
function( Hst0.ls, x ) {
tau <- length(Hst0.ls)
sHst0.ls <- list()
for(i in 1:tau) {
sHst0.ls[[i]] <- t( ( t(Hst0.ls[[i]]) - x$h.mean ) / x$h.sd )
}
return(sHst0.ls)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/applystnd.Hst.ls.R
|
create.rm.ndx.ls <-
function(n, xincmnt=10) {
rm.ndx.ls <- list()
for(i in 1:xincmnt) { xrm.ndxs <- seq(i, n+xincmnt, by=xincmnt) ; xrm.ndxs <- xrm.ndxs[ xrm.ndxs <= n ] ; rm.ndx.ls[[i]] <- xrm.ndxs }
return( rm.ndx.ls )
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/create.rm.ndx.ls.R
|
crispify <-
function( locs1, locs2, Z.delta, z.lags.vec, geodesic, alpha, flatten, self.refs, lags, stnd.d=FALSE, log10cutoff=-16 ) {
## dyn.load("~/Files/Creations/C/widals.so")
n1 <- nrow(locs1) #### length n
n2 <- nrow(locs2) #### length n*k
tau <- nrow(Z.delta)
n.Zd <- ncol(Z.delta)
Z.out <- rep(0, tau * n1)
z.rep.in <- rep( 0:(n.Zd-1), length.out=n2 )
t.start <- max(0, -min(lags))
t.stop <- min(tau, tau-max(lags))
t.s.s <- c(t.start, t.stop)
if( geodesic ) {
rlocs1 <- pi*locs1[ , 1:2 ]/180
rlocs2 <- pi*locs2[ , 1:2 ]/180
Z.out <- .C("crispify", as.double(cos(rlocs1[,1])*cos(rlocs1[,2])), as.double(cos(rlocs1[,1])*sin(rlocs1[,2])), as.double(sin(rlocs1[,1])), as.double(locs1[ ,3]),
as.double(cos(rlocs2[,1])*cos(rlocs2[,2])), as.double(cos(rlocs2[,1])*sin(rlocs2[,2])), as.double(sin(rlocs2[,1])), as.double(locs2[ ,3]),
as.double( as.vector(Z.delta) ), as.double( Z.out ),
as.double( alpha ), as.double( flatten ),
as.integer( self.refs ), as.integer( length(self.refs) ), as.integer( z.lags.vec ), as.integer( z.rep.in ), as.integer(n.Zd),
as.integer(n1), as.integer(n2), as.integer(tau), as.integer(stnd.d), as.integer(t.s.s), as.integer(geodesic), as.double(log10cutoff) )[[10]]
} else {
Z.out <- .C("crispify", as.double( locs1[ , 1] ), as.double( locs1[ , 2] ), as.double( 0 ), as.double( locs1[ , 3] ),
as.double( locs2[ , 1] ), as.double( locs2[ , 2] ), as.double( 0 ), as.double( locs2[ , 3] ),
as.double( as.vector(Z.delta) ), as.double( Z.out ),
as.double( alpha ), as.double( flatten ),
as.integer( self.refs ), as.integer( length(self.refs) ), as.integer( z.lags.vec ), as.integer( z.rep.in ), as.integer(n.Zd),
as.integer(n1), as.integer(n2), as.integer(tau), as.integer(stnd.d), as.integer(t.s.s), as.integer(geodesic), as.double(log10cutoff) )[[10]]
}
dim(Z.out) <- c(tau, n1)
return(Z.out)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/crispify.R
|
distance <-
function( locs1, locs2, geodesic=FALSE ) {##### treats 1st column as lat
#dyn.load("~/Files/Creations/C/distance.so")
n1 <- nrow(locs1)
n2 <- nrow(locs2)
#D.out <- matrix(0, n1, n2)
d.out <- rep(0, n1 * n2)
if( geodesic ) {
D.Mx <- .C("distance_geodesic_AB", as.double(locs1[ ,1]*pi/180), as.double(locs1[ ,2]*pi/180),
as.double(locs2[ ,1]*pi/180), as.double(locs2[ ,2]*pi/180), as.double(d.out), as.integer(n1), as.integer(n2) )[[5]]
} else {
D.Mx <- .C("distance_AB", as.double(locs1[ ,1]), as.double(locs1[ ,2]),
as.double(locs2[ ,1]), as.double(locs2[ ,2]), as.double(d.out), as.integer(n1), as.integer(n2) )[[5]]
}
D.out <- matrix(D.Mx, n1, n2)
return(D.out)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/distance.R
|
dlog.norm <-
function(n, center, sd) {
return( exp( rnorm(n, log( center ), sd) ) )
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/dlog.norm.R
|
fun.load.hals.a <-
function() {
run.parallel <- run.parallel
if( run.parallel ) {
sfExport("Z", "Hs", "Ht", "Hst.ls", "b.lag", "train.rng", "test.rng")
suppressWarnings(sfLibrary("widals", character.only=TRUE))
}
p.ndx.ls <- list( c(1,2) )
## assign( "p.ndx.ls", p.ndx.ls, pos=globalenv() )
p.ndx.ls <<- p.ndx.ls
f.d <- list( dlog.norm, dlog.norm, dlog.norm, dlog.norm, dlog.norm )
## assign( "f.d", f.d, pos=globalenv() )
f.d <<- f.d
FUN.MH <- function(jj, GP.mx, X) {
Z <- Z
Hs <- Hs
Ht <- Ht
Hst.ls <- Hst.ls
b.lag <- b.lag
train.rng <- train.rng
Z.als <- Hals.snow( jj, Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, b.lag=b.lag, GP.mx=GP.mx )
resids <- Z - Z.als
our.cost <- sqrt( mean( resids[ train.rng, ]^2 ) )
return( our.cost )
}
##assign( "FUN.MH", FUN.MH, pos=globalenv() )
FUN.MH <<- FUN.MH
#FUN.GP <- NULL
FUN.GP <- function(GP.mx) {
rho.upper.limit <- rho.upper.limit
rgr.lower.limit <- rgr.lower.limit
GP.mx[ GP.mx[ , 1] > rho.upper.limit, 1 ] <- rho.upper.limit
GP.mx[ GP.mx[ , 2] < rgr.lower.limit, 2 ] <- rgr.lower.limit
return(GP.mx)
}
## assign( "FUN.GP", FUN.GP, pos=globalenv() )
FUN.GP <<- FUN.GP
FUN.I <- function(envmh, X) {
cat( "Improvement ---> ", envmh$current.best, " ---- " , envmh$GP, "\n" )
}
## assign( "FUN.I", FUN.I, pos=globalenv() )
FUN.I <<- FUN.I
FUN.EXIT <- function(envmh, X) {
Z <- Z
Hs <- Hs
Ht <- Ht
Hst.ls <- Hst.ls
b.lag <- b.lag
train.rng <- train.rng
test.rng <- test.rng
## GP <- GP
GP.mx <- matrix(envmh$GP, 1, length(envmh$GP))
Z.als <- Hals.snow( 1, Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, b.lag=b.lag, GP.mx=GP.mx )
resids <- Z - Z.als
our.cost <- sqrt( mean( resids[ test.rng, ]^2 ) )
cat( envmh$GP, " -- ", our.cost, "\n" )
## assign( "Z.als", Z.als, pos=globalenv() )
## assign( "our.cost", our.cost, pos=globalenv() )
## assign( "GP", envmh$GP, pos=globalenv() )
Z.als <<- Z.als
our.cost <<- our.cost
GP <- envmh$GP
GP <<- GP
cat( paste( "GP <- c(", paste(format(GP,digits=5), collapse=", "), ") ### ", format(our.cost, width=6), "\n", sep="" ) )
}
## assign( "FUN.EXIT", FUN.EXIT, pos=globalenv() )
FUN.EXIT <<- FUN.EXIT
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/fun.load.hals.a.R
|
fun.load.hals.fill <-
function() {
run.parallel <- run.parallel
if( run.parallel ) {
sfExport("Z", "Hs", "Ht", "Hst.ls", "b.lag", "train.rng", "test.rng", "Z.na")
suppressWarnings(sfLibrary("widals", character.only=TRUE))
}
p.ndx.ls <- list( c(1,2) )
## assign( "p.ndx.ls", p.ndx.ls, pos=globalenv() )
p.ndx.ls <<- p.ndx.ls
f.d <- list( dlog.norm, dlog.norm, dlog.norm, dlog.norm, dlog.norm )
## assign( "f.d", f.d, pos=globalenv() )
f.d <<- f.d
FUN.MH <- function(jj, GP.mx, X) {
Z.na <- Z.na
Z <- Z
Hs <- Hs
Ht <- Ht
Hst.ls <- Hst.ls
b.lag <- b.lag
train.rng <- train.rng
Z.als <- Hals.snow( jj, Z=X$Z.fill, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, b.lag=b.lag, GP.mx=GP.mx )
##if( min(Z, na.rm=TRUE) >= 0 ) { Z.als[ Z.als < 0 ] <- 0 } ############ DZ EDIT
resids <- (Z - Z.als)[ train.rng, ]
our.cost <- sqrt( mean( resids[ !Z.na[ train.rng, ] ]^2 ) )
return( our.cost )
}
## assign( "FUN.MH", FUN.MH, pos=globalenv() )
FUN.MH <<- FUN.MH
#FUN.GP <- NULL
#rgr.lower.limit <- 10^(-7)
#d.alpha.lower.limit <- 10^(-2)
#rho.upper.limit <- 10^(-2)
FUN.GP <- function(GP.mx) {
rho.upper.limit <- rho.upper.limit
rgr.lower.limit <- rgr.lower.limit
GP.mx[ GP.mx[ , 1] > rho.upper.limit, 1 ] <- rho.upper.limit
GP.mx[ GP.mx[ , 2] < rgr.lower.limit, 2 ] <- rgr.lower.limit
return(GP.mx)
}
## assign( "FUN.GP", FUN.GP, pos=globalenv() )
FUN.GP <<- FUN.GP
FUN.I <- function(envmh, X) {
Hs <- Hs
Ht <- Ht
Hst.ls <- Hst.ls
b.lag <- b.lag
Z.na <- Z.na
GP.mx <- matrix(envmh$GP, 1, length(envmh$GP))
Z.als <- Hals.snow( 1, Z=X$Z.fill, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, b.lag=b.lag, GP.mx=GP.mx )
##if( min(Z, na.rm=TRUE) >= 0 ) { Z.als[ Z.als < 0 ] <- 0 } ############ DZ EDIT
## assign( "Z.als", Z.als, envir=globalenv() )
Z.als <<- Z.als
Z.als <- Z.clean.up(Z.als)
X$Z.fill[ Z.na ] <- Z.als[ Z.na ]
X$Z.fill[ is.na(X$Z.fill) ] <- mean( X$Z.fill, na.rm=TRUE ) #### fill in a few NAs in our Zhats
cat( "Improvement ---> ", envmh$current.best, " ---- " , envmh$GP, "\n" )
return(X)
}
## assign( "FUN.I", FUN.I, pos=globalenv() )
FUN.I <<- FUN.I
FUN.EXIT <- function(envmh, X) {
our.cost <- envmh$current.best
## assign( "our.cost", our.cost, pos=globalenv() )
## assign( "Z.fill", X$Z.fill, envir=globalenv() )
## assign( "GP", envmh$GP, pos=globalenv() )
our.cost <<- our.cost
Z.fill <- X$Z.fill
Z.fill <<- Z.fill
GP <- envmh$GP
GP <<- GP
cat( paste( "GP <- c(", paste(format(envmh$GP,digits=5), collapse=", "), ") ### ", format(our.cost, width=6), "\n", sep="" ) )
}
## assign( "FUN.EXIT", FUN.EXIT, pos=globalenv() )
FUN.EXIT <<- FUN.EXIT
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/fun.load.hals.fill.R
|
fun.load.widals.a <-
function() {
run.parallel <- run.parallel
lags <- lags
rm.ndx <- rm.ndx
if( run.parallel ) {
sfExport("Z", "Hs", "Ht", "Hst.ls", "locs", "lags", "b.lag", "cv", "rm.ndx", "train.rng", "test.rng", "xgeodesic", "ltco", "stnd.d")
suppressWarnings(sfLibrary("widals", character.only=TRUE))
}
if( length(lags) == 1 & lags[1] == 0 ) {
p.ndx.ls <- list( c(1,2), c(3,5) )
} else {
p.ndx.ls <- list( c(1,2), c(3,4,5) )
}
## assign( "p.ndx.ls", p.ndx.ls, pos=globalenv() )
p.ndx.ls <<- p.ndx.ls
f.d <- list( dlog.norm, dlog.norm, dlog.norm, dlog.norm, dlog.norm )
## assign( "f.d", f.d, pos=globalenv() )
f.d <<- f.d
FUN.MH <- function(jj, GP.mx, X) {
Z <- Z
Hs <- Hs
Ht <- Ht
Hst.ls <- Hst.ls
b.lag <- b.lag
lags <- lags
cv <- cv
xgeodesic <- xgeodesic
stnd.d <- stnd.d
ltco <- ltco
train.rng <- train.rng
locs <- locs
Z.wid <- widals.snow(jj, rm.ndx=rm.ndx, Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, locs=locs, lags=lags, b.lag=b.lag, cv=cv, geodesic=xgeodesic,
wrap.around=NULL, GP.mx, stnd.d=stnd.d, ltco=ltco)
if( min(Z, na.rm=TRUE) >= 0 ) { Z.wid[ Z.wid < 0 ] <- 0 } ############ DZ EDIT
Z.wid <- Z.clean.up(Z.wid)
resids <- Z[ , unlist(rm.ndx)] - Z.wid[ , unlist(rm.ndx)]
our.cost <- sqrt( mean( resids[ train.rng, ]^2 ) )
if( is.nan(our.cost) ) { our.cost <- Inf }
return( our.cost )
}
## assign( "FUN.MH", FUN.MH, pos=globalenv() )
FUN.MH <<- FUN.MH
#FUN.GP <- NULL
FUN.GP <- function(GP.mx) {
rho.upper.limit <- rho.upper.limit
rgr.lower.limit <- rgr.lower.limit
d.alpha.lower.limit <- d.alpha.lower.limit
GP.mx[ GP.mx[ , 1] > rho.upper.limit, 1 ] <- rho.upper.limit
GP.mx[ GP.mx[ , 2] < rgr.lower.limit, 2 ] <- rgr.lower.limit
GP.mx[ GP.mx[ , 3] < d.alpha.lower.limit, 3 ] <- d.alpha.lower.limit
xperm <- order(GP.mx[ , 3, drop=FALSE])
GP.mx <- GP.mx[ xperm, , drop=FALSE]
return(GP.mx)
}
## assign( "FUN.GP", FUN.GP, pos=globalenv() )
FUN.GP <<- FUN.GP
FUN.I <- function(envmh, X) {
cat( "Improvement ---> ", envmh$current.best, " ---- " , envmh$GP, "\n" )
}
## assign( "FUN.I", FUN.I, pos=globalenv() )
FUN.I <<- FUN.I
FUN.EXIT <- function(envmh, X) {
rm.ndx <- rm.ndx
Z <- Z
Hs <- Hs
Ht <- Ht
Hst.ls <- Hst.ls
locs <- locs
lag <- lag
b.lag <- b.lag
cv <- cv
xgeodesic <- xgeodesic
stnd.d <- stnd.d
ltco <- ltco
test.rng <- test.rng
GP.mx <- matrix(envmh$GP, 1, length(envmh$GP))
Z.wid <- widals.snow(1, rm.ndx=rm.ndx, Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, locs=locs, lags=lags, b.lag=b.lag, cv=cv, geodesic=xgeodesic,
wrap.around=NULL, GP.mx, stnd.d=stnd.d, ltco=ltco)
if( min(Z, na.rm=TRUE) >= 0 ) { Z.wid[ Z.wid < 0 ] <- 0 } ############ DZ EDIT
## assign( "Z.wid", Z.wid, envir=globalenv() )
Z.wid <<- Z.wid
Z.wid <- Z.clean.up(Z.wid)
resids <- Z[ , unlist(rm.ndx)] - Z.wid[ , unlist(rm.ndx)]
our.cost <- sqrt( mean( resids[ test.rng, ]^2 ) )
if( is.nan(our.cost) ) { our.cost <- Inf }
cat( envmh$GP, " -- ", our.cost, "\n" )
## assign( "our.cost", our.cost, pos=globalenv() )
## assign( "GP", envmh$GP, pos=globalenv() )
our.cost <<- our.cost
GP <- envmh$GP
GP <<- GP
cat( paste( "GP <- c(", paste(format(GP,digits=5), collapse=", "), ") ### ", format(our.cost, width=6), "\n", sep="" ) )
}
## assign( "FUN.EXIT", FUN.EXIT, pos=globalenv() )
FUN.EXIT <<- FUN.EXIT
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/fun.load.widals.a.R
|
fun.load.widals.fill <-
function() {
lags <- lags
run.parallel <- run.parallel
if( run.parallel ) {
sfExport("Z", "Hs", "Ht", "Hst.ls", "locs", "lags", "b.lag", "cv", "rm.ndx", "train.rng", "test.rng", "xgeodesic", "ltco", "stnd.d", "Z.na")
suppressWarnings(sfLibrary("widals", character.only=TRUE))
}
if( length(lags) == 1 & lags[1] == 0 ) {
p.ndx.ls <- list( c(1,2), c(3,5) )
} else {
p.ndx.ls <- list( c(1,2), c(3,4,5) )
}
## assign( "p.ndx.ls", p.ndx.ls, pos=globalenv() )
p.ndx.ls <<- p.ndx.ls
f.d <- list( dlog.norm, dlog.norm, dlog.norm, dlog.norm, dlog.norm )
## assign( "f.d", f.d, pos=globalenv() )
f.d <<- f.d
FUN.MH <- function(jj, GP.mx, X) {
rm.ndx <- rm.ndx
Hs <- Hs
Ht <- Ht
Hst.ls <- Hst.ls
locs <- locs
lags <- lags
b.lag <- b.lag
cv <- cv
xgeodesic <- xgeodesic
stnd.d <- stnd.d
ltco <- ltco
Z <- Z
train.rng <- train.rng
Z.na <- Z.na
Z.wid <- widals.snow(jj, rm.ndx=rm.ndx, Z=X$Z.fill, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, locs=locs, lags=lags, b.lag=b.lag,
cv=cv, geodesic=xgeodesic, wrap.around=NULL, GP.mx=GP.mx, stnd.d=stnd.d, ltco=ltco )
##if( min(Z, na.rm=TRUE) >= 0 ) { Z.wid[ Z.wid < 0 ] <- 0 } ############ DZ EDIT
resids <- (Z - Z.wid)[ train.rng, unlist(rm.ndx) ]
our.cost <- sqrt( mean( resids[ !Z.na[ train.rng, unlist(rm.ndx) ] ]^2 ) )
return( our.cost )
}
## assign( "FUN.MH", FUN.MH, pos=globalenv() )
FUN.MH <<- FUN.MH
#FUN.GP <- NULL
FUN.GP <- function(GP.mx) {
rho.upper.limit <- rho.upper.limit
rgr.lower.limit <- rgr.lower.limit
d.alpha.lower.limit <- d.alpha.lower.limit
GP.mx[ GP.mx[ , 1] > rho.upper.limit, 1 ] <- rho.upper.limit
GP.mx[ GP.mx[ , 2] < rgr.lower.limit, 2 ] <- rgr.lower.limit
GP.mx[ GP.mx[ , 3] < d.alpha.lower.limit, 3 ] <- d.alpha.lower.limit
xperm <- order(GP.mx[ , 3, drop=FALSE])
GP.mx <- GP.mx[ xperm, , drop=FALSE]
return(GP.mx)
}
## assign( "FUN.GP", FUN.GP, pos=globalenv() )
FUN.GP <<- FUN.GP
FUN.I <- function(envmh, X) {
rm.ndx <- rm.ndx
Hs <- Hs
Ht <- Ht
Hst.ls <- Hst.ls
locs <- locs
lags <- lags
b.lag <- b.lag
cv <- cv
xgeodesic <- xgeodesic
stnd.d <- stnd.d
ltco <- ltco
Z.na <- Z.na
GP.mx <- matrix(envmh$GP, 1, length(envmh$GP))
Z.wid <- widals.snow(1, rm.ndx=rm.ndx, Z=X$Z.fill, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, locs=locs, lags=lags, b.lag=b.lag,
cv=cv, geodesic=xgeodesic, wrap.around=NULL, GP.mx=GP.mx, stnd.d=stnd.d, ltco=ltco )
### if( min(Z, na.rm=TRUE) >= 0 ) { Z.wid[ Z.wid < 0 ] <- 0 } ############ DZ EDIT
## assign( "Z.wid", Z.wid, envir=globalenv() )
Z.wid <<- Z.wid
Z.wid <- Z.clean.up(Z.wid)
X$Z.fill[ Z.na ] <- Z.wid[ Z.na ]
X$Z.fill[ is.na(X$Z.fill) ] <- mean( X$Z.fill, na.rm=TRUE )
cat( "Improvement ---> ", envmh$current.best, " ---- " , envmh$GP, "\n" )
return(X)
}
## assign( "FUN.I", FUN.I, pos=globalenv() )
FUN.I <<- FUN.I
FUN.EXIT <- function(envmh, X) {
our.cost <- envmh$current.best
## assign( "our.cost", our.cost, pos=globalenv() )
## assign( "Z.fill", X$Z.fill, envir=globalenv() )
## assign( "GP", envmh$GP, pos=globalenv() )
our.cost <<- our.cost
Z.fill <- X$Z.fill
Z.fill <<- Z.fill
GP <- envmh$GP
GP <<- GP
cat( paste( "GP <- c(", paste(format(envmh$GP,digits=5), collapse=", "), ") ### ", format(our.cost, width=6), "\n", sep="" ) )
}
## assign( "FUN.EXIT", FUN.EXIT, pos=globalenv() )
FUN.EXIT <<- FUN.EXIT
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/fun.load.widals.fill.R
|
fuse.Hst.ls <-
function(Hst.ls1, Hst.ls2) {
tau <- length(Hst.ls1)
for(i in 1:tau) {
Hst.ls1[[i]] <- cbind( Hst.ls1[[i]], Hst.ls2[[i]] )
}
return(Hst.ls1)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/fuse.Hst.ls.R
|
load.Hst.ls.2Zs <-
function(Z, Z.na, Hst.ls.Z, xwhich, rgr.lags=c(0)) {
tau <- tau
min.ndx <- max(1, -min(rgr.lags)+1)
max.ndx <- min(tau, tau-max(rgr.lags))
for(i in min.ndx:max.ndx) {
zi.na <- Z.na[ i, ]
Hst.ls.Z[[i]][ !zi.na , 2*xwhich-1 ] <- Z[i+rgr.lags, !zi.na ]
Hst.ls.Z[[i]][ zi.na , 2*xwhich-1 ] <- 0
Hst.ls.Z[[i]][ zi.na , 2*xwhich ] <- Z[i+rgr.lags, zi.na ]
Hst.ls.Z[[i]][ !zi.na , 2*xwhich ] <- 0
}
return(Hst.ls.Z)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/load.Hst.ls.2Zs.R
|
load.Hst.ls.Z <-
function(Z, Hst.ls.Z, xwhich, rgr.lags=c(0)) {
tau <- tau
min.ndx <- max(1, -min(rgr.lags)+1)
max.ndx <- min(tau, tau-max(rgr.lags))
for(i in min.ndx:max.ndx) {
Hst.ls.Z[[i]][ , xwhich ] <- t( Z[i+rgr.lags, ] )
}
return(Hst.ls.Z)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/load.Hst.ls.Z.R
|
rm.cols.Hst.ls <-
function(Hst.ls, rm.col.ndx) {
tau <- length(Hst.ls)
for(i in 1:tau) {
Hst.ls[[i]] <- Hst.ls[[i]][ , -rm.col.ndx, drop=FALSE ]
}
return(Hst.ls)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/rm.cols.Hst.ls.R
|
stnd.Hs <-
function(Hs, Hs0=NULL, intercept=TRUE) {
n <- nrow(Hs)
h.mean <- apply(Hs, 2, mean)
h.sd <- apply( t(t(Hs)-h.mean) , 2, function(x) { sqrt( sum(x^2) ) } )
h.sd[ h.sd == 0 ] <- 1
sHs <- t( ( t(Hs) - h.mean ) / h.sd )
if( intercept ) { sHs[ , 1] <- 1 / sqrt(n) }
sHs0 <- NULL
if( !is.null(Hs0) ) {
sHs0 <- t( ( t(Hs0) - h.mean ) / h.sd )
if( intercept ) { sHs0[ , 1] <- 1 / sqrt(n) }
}
ls.out <- list( "sHs"=sHs, "sHs0"=sHs0, "h.mean"=h.mean, "h.sd"=h.sd, "n"=n, "intercept"=intercept )
return(ls.out)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/stnd.Hs.R
|
stnd.Hst.ls <-
function( Hst.ls, Hst0.ls=NULL ) {
tau <- length(Hst.ls)
big.sum <- 0
for(i in 1:tau) {
big.sum <- big.sum + apply( Hst.ls[[i]] , 2, mean )
}
h.mean <- big.sum / tau
sHst.ls <- list()
big.sum.mx <- 0
for(i in 1:tau) {
sHst.ls[[i]] <- t( t(Hst.ls[[i]]) - h.mean )
big.sum.mx <- big.sum.mx + crossprod( sHst.ls[[i]] )
}
cov.mx <- big.sum.mx / tau
sqrtXX <- 1 / sqrt( diag(cov.mx) )
for(i in 1:tau) {
sHst.ls[[i]] <- t( t(sHst.ls[[i]]) * sqrtXX )
}
sHst0.ls <- NULL
if( !is.null(Hst0.ls) ) {
sHst0.ls <- list()
for(i in 1:tau) {
sHst0.ls[[i]] <- t( ( t(Hst0.ls[[i]]) - h.mean ) * sqrtXX )
}
}
ls.out <- list( "sHst.ls"=sHst.ls, "sHst0.ls"=sHst0.ls, "h.mean"=h.mean, "h.sd"= 1/sqrtXX )
return( ls.out )
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/stnd.Hst.ls.R
|
stnd.Ht <-
function(Ht, n) {
h.mean <- apply(Ht, 2, mean)
sHt <- t( t(Ht) - h.mean )
sHt <- t( t(sHt) / apply( sHt, 2, function(x) { sqrt( sum(x^2) ) } ) )
sHt <- sHt * sqrt( nrow(Ht) / n )
return(sHt)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/stnd.Ht.R
|
subsetsites.Hst.ls <-
function( Hst.ls, xmask ) {
tau <- length(Hst.ls)
Hst.ls.out <- list()
for(i in 1:tau) {
Hst.ls.out[[i]] <- Hst.ls[[i]][ xmask, , drop=FALSE]
}
return( Hst.ls.out )
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/subsetsites.Hst.ls.R
|
unif.mh <-
function(n, center, sd) {
w <- sd * sqrt(3)
a <- center - w
b <- center + w
cat(a, b, "\n" )
x <- runif(1, a, b)
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/unif.mh.R
|
unload.Hst.ls <-
function(Hst.ls, which.col, rgr.lags) {
n <- nrow(Hst.ls[[1]])
tau <- length(Hst.ls)
Z.out <- matrix(NA, tau, n)
min.ndx <- max(1, -min(rgr.lags)+1)
max.ndx <- min(tau, tau-max(rgr.lags))
for(i in min.ndx:max.ndx) {
Z.out[i-rgr.lags, ] <- Hst.ls[[i]][ , which.col ]
}
return(Z.out)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/unload.Hst.ls.R
|
widals.predict <-
function(Z, Hs, Ht, Hst.ls, locs, lags, b.lag, Hs0, Hst0.ls, locs0, geodesic=FALSE, wrap.around=NULL, GP, stnd.d=FALSE, ltco=-16) {
tau <- nrow(Z)
n <- nrow(locs)
k <- length(lags)
n0 <- nrow(locs0)
rho <- GP[ 1 ]
reg <- GP[ 2 ]
alpha <- GP[ 3 ]
beta <- GP[ 4 ]
flatten <- GP[ 5 ]
locs0.3D <- cbind( locs0, rep(0, n0) )
locs.long.3D <- cbind( rep(locs[ ,1], k), rep(locs[ ,2], k), beta*rep( lags, each=n ) )
z.lags.vec <- rep( lags, each=n )
# xalsp <- als.prepare(NULL, Z, lags, is.na(Z), tt.rng=1:nrow(Z)) #### tt.rng not used
# obsZatLags <- xalsp$X.sub
# rm(xalsp)
ALS <- H.als.b(Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, rho=rho, reg=reg, b.lag=b.lag, Hs0=Hs0, Ht0=Ht, Hst0.ls=Hst0.ls)
Y.als <- ALS$Z.hat ; dim(Y.als)
Y0.als <- ALS$Z0.hat ; dim(Y0.als)
rm(ALS)
#yalsp <- als.prepare(NULL, Y.als, lags, is.na(Y.als), tt.rng=1:nrow(Y.als)) #### tt.rng not used
Z.delta <- Z - Y.als
Z.delta <- Z.clean.up( Z.delta )
#rm(yalsp)
# y0alsp <- als.prepare(NULL, Y0.als, lags, is.na(Y.als), tt.rng=1:nrow(Y.als)) #### tt.rng not used
# y0hat <- y0alsp$Y.sub
# rm(y0alsp)
# deltaZatLags[ is.na(deltaZatLags) ] <- mean(deltaZatLags, na.rm=TRUE)
Z.adj <- crispify( locs1=locs0.3D, locs2=locs.long.3D, Z.delta=Z.delta, z.lags.vec=z.lags.vec, geodesic=geodesic,
alpha=alpha, flatten=flatten, self.refs=c(-1), lags=lags, stnd.d=stnd.d, log10cutoff=ltco )
## sum( is.na(Z)
# Y0.idw <- y0hat + Z.adj
# Z0.idw <- y.unalign(Y0.idw, lags)
Z0.wid <- Y0.als + Z.adj
# assign( "ALS.Y0", y0hat, pos=.GlobalEnv )
# assign( "ALS.actual", obsZatLags, pos=.GlobalEnv )
# assign( "ALS.pred", predZatLags, pos=.GlobalEnv )
return(Z0.wid)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/widals.predict.R
|
widals.snow <-
function(j, rm.ndx, Z, Hs, Ht, Hst.ls, locs, lags, b.lag, cv=0, geodesic=FALSE, wrap.around=NULL, GP.mx, stnd.d=FALSE, ltco=-16) {
tau <- nrow(Z)
n <- ncol(Z)
k <- length(lags)
rho <- GP.mx[ j, 1 ]
reg <- GP.mx[ j, 2 ]
alpha <- GP.mx[ j, 3 ]
beta <- GP.mx[ j, 4 ]
flatten <- GP.mx[ j, 5 ]
locs.3D <- cbind( locs, rep(0, n) )
locs.long.3D <- cbind( rep(locs[ ,1], k), rep(locs[ ,2], k) , beta*rep( lags, each=n ) )
z.lags.vec <- rep( lags, each=n )
#Z.obsAtLags <- als.prepare(NULL, Z, lags, Z.na=NULL, tt.rng=1:nrow(Z))$X.sub #### tt.rng not used
use.Hst.ls <- !is.null(Hst.ls)
if( cv <= 0 ) {
Y.als <- H.als.b(Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, rho=rho, reg=reg, b.lag=b.lag, Hs0=NULL, Ht0=NULL, Hst0.ls=NULL)$Z.hat
## assign( "Y.als", Y.als, pos=.GlobalEnv )
Y.als <<- Y.als
#yalsp <- als.prepare(NULL, Y.als, lags, Z.na=NULL, tt.rng=1:nrow(Y.als)) #### tt.rng not used
#rm( Y.als )
Z.delta <- Z - Y.als
Z.delta <- Z.clean.up( Z.delta )
#rm(Z.obsAtLags)
#Y0.als <- yalsp$Y.sub
#rm(yalsp)
if( cv == -1 ) { ##################### zero only self ref sites at lag 0
self.refs <- (which( lags == 0 ) - 1)*n
}
if( cv == -2 ) { ##################### zero all self ref sites across all lags
self.refs <- I(0:(k-1)) * n
}
Z.adj <- crispify( locs1=locs.3D, locs2=locs.long.3D, Z.delta=Z.delta, z.lags.vec=z.lags.vec, geodesic=geodesic,
alpha=alpha, flatten=flatten, self.refs=self.refs, lags=lags, stnd.d=stnd.d, log10cutoff=ltco )
## mean func pred + ( obs @ lags - mean func pred @ lags ) %*% Weights
#Y.idw <- Y0.als + Z.adj
Z.wid <- Y.als + Z.adj
}
if( cv == 1 | cv == 2 ) { #### cv=1 drops only site at lag 0, cv=2 drops site for all time lags #### only uses cv = 2
Z.wid <- matrix(NA, tau, n )
loc.0 <- which( lags == 0 )
for( kk in 1:length(rm.ndx) ) {
ii <- rm.ndx[[kk]]
if( cv == 1 ) { drop.ndx <- (loc.0-1)*n + ii } else { drop.ndx <- ( rep( 1:k, each=length(ii) ) - 1 )*n + ii }
if( use.Hst.ls ) {
red.Hst.ls <- list()
for(i in 1:tau) {
red.Hst.ls[[i]] <- Hst.ls[[i]][ -ii, , drop=FALSE]
}
} else {
red.Hst.ls <- NULL
}
Y.als <- H.als.b(Z=Z[ , -ii, drop=FALSE], Hs=Hs[ -ii, , drop=FALSE], Ht=Ht, Hst.ls=red.Hst.ls,
rho=rho, reg=reg, b.lag=b.lag, Hs0=Hs, Ht0=Ht, Hst0.ls=Hst.ls)$Z0.hat
#yalsp <- als.prepare(NULL, Y.als, lags, is.na(Y.als), tt.rng=1:nrow(Y.als)) #### tt.rng not used
# rm(Y.als)
Z.delta.drop <- Z[ , -ii, drop=FALSE] - Y.als[ , -ii, drop=FALSE]
Z.delta.drop <- Z.clean.up( Z.delta.drop )
z.lags.vec.drop <- z.lags.vec[ -drop.ndx ]
#Y0.als <- yalsp$Y.sub[ , ii]
# rm(yalsp)
Z.adj <- crispify( locs1=locs.3D[ ii, , drop=FALSE ], locs2=locs.long.3D[ -drop.ndx , , drop=FALSE ],
Z.delta=Z.delta.drop, z.lags.vec=z.lags.vec.drop, geodesic=geodesic,
alpha=alpha, flatten=flatten, self.refs=c(-1), lags=lags, stnd.d=stnd.d, log10cutoff=ltco )
Z.wid[ , ii] <- Y.als[ , ii ] + Z.adj
}
}
return(Z.wid)
}
|
/scratch/gouwar.j/cran-all/cranData/widals/R/widals.snow.R
|
### R code from vignette source 'funwithfunload.Snw'
###################################################
### code chunk number 1: funwithfunload.Snw:127-130
###################################################
options(width=49)
options(prompt=" ")
options(continue=" ")
###################################################
### code chunk number 2: funwithfunload.Snw:135-181 (eval = FALSE)
###################################################
## options(stringsAsFactors=FALSE)
##
## library(snowfall)
##
## k.cpus <- 2 #### set the number of cpus for snowfall
##
## library(widals)
## data(O3)
##
## Z.all <- as.matrix(O3$Z)[366:730, ]
## locs.all <- O3$locs[ , c(2,1)]
## hsa.all <- O3$helevs/500
##
## xdate <- rownames(Z.all)
##
## tau <- nrow(Z.all)
## n.all <- ncol(Z.all)
##
## xgeodesic <- TRUE
##
## Z <- Z.all
## locs <- locs.all
## n <- n.all
##
## dateDate <- strptime(xdate, "%Y%m%d")
## doy <- as.integer(format(dateDate, "%j"))
##
## Ht <- cbind( sin(2*pi*doy/365), cos(2*pi*doy/365) )
## Hs.all <- cbind(matrix(1, nrow=n.all), hsa.all)
## Hisa.ls <- H.Earth.solar(locs[ , 2], locs[ , 1], dateDate)
##
## Hst.ls.all2 <- list()
## for(tt in 1:tau) {
## Hst.ls.all2[[tt]] <- cbind(Hisa.ls[[tt]], Hisa.ls[[tt]]*hsa.all)
## colnames(Hst.ls.all2[[tt]]) <- c("ISA", "ISAxElev")
## }
## Hst.ls <- Hst.ls.all2
## Hs <- Hs.all
## Ht.original <- Ht
##
##
## train.rng <- 30:tau
## test.rng <- train.rng
##
## k.glob <- 10
## run.parallel <- TRUE
###################################################
### code chunk number 3: funwithfunload.Snw:188-218 (eval = FALSE)
###################################################
##
##
## FUN.source <- fun.load.widals.a
##
## d.alpha.lower.limit <- 0
## rho.upper.limit <- 100
## rgr.lower.limit <- 10^(-7)
##
## GP <- c(1/10, 1, 0.01, 3, 1)
##
## ############# pseudo cross-validation
## rm.ndx <- 1:n
## cv <- -2
## lags <- c(0)
## b.lag <- -1
##
## sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
## ltco <- -10
## stnd.d <- TRUE
##
## FUN.GP <- NULL
##
## sfInit(TRUE, k.cpus)
## FUN.source()
##
## set.seed(99999)
## MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
## k.glob, k.loc.coef=7, X = NULL)
## sfStop()
## #### 11.90536
###################################################
### code chunk number 4: funwithfunload.Snw:224-249 (eval = FALSE)
###################################################
## k.glob <- 10
##
## FUN.source <- fun.load.widals.a
##
## GP <- c(1/10, 1, 0.01, 3, 1)
##
## ######### true spacial cross-validation
## rm.ndx <- create.rm.ndx.ls(n, 14)
## cv <- 2
## lags <- c(0)
## b.lag <- 0
##
## sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
## ltco <- -10
##
## FUN.GP <- NULL
##
## sfInit(TRUE, k.cpus)
## FUN.source()
##
## set.seed(99999)
## MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
## k.glob, k.loc.coef=7, X=NULL)
## sfStop()
## #### 12.11686
###################################################
### code chunk number 5: funwithfunload.Snw:260-278 (eval = FALSE)
###################################################
## library(LatticeKrig)
##
## xxb <- 4
## yyb <- 4
## center <- as.matrix(expand.grid( seq(0, 1, length=xxb), seq(0, 1, length=yyb)))
##
## ###### run together
## ffunit <- function(x) { return( (x-min(x)) / (max(x)-min(x)) ) }
## locs.unit <- apply(locs, 2, ffunit)
## locs.unit <- matrix(as.vector(locs.unit), ncol=2)
## ###### run togther
##
## xPHI <- Radial.basis(as.matrix(locs.unit), center, 0.5)
## Hs.lkrig <- matrix(NA, nrow(locs), xxb*yyb)
## for(i in 1:nrow(locs)) {
## Hs.lkrig[i, ] <- xPHI[i]
## }
## Hs.lkrig <- Hs.lkrig[ , -which( apply(Hs.lkrig, 2, sum) < 0.1 ), drop=FALSE ]
###################################################
### code chunk number 6: funwithfunload.Snw:290-302 (eval = FALSE)
###################################################
## XA.Hs <- cbind(rep(1,n), hsa.all)
## XA.Ht <- Ht.original
## XA.Hst.ls <- Hst.ls
##
## Hst.sumup(XA.Hst.ls, XA.Hs, XA.Ht)
##
##
## XB.Hs <- 10*Hs.lkrig
## XB.Ht <- NULL
## XB.Hst.ls <- NULL
##
## Hst.sumup(XB.Hst.ls, XB.Hs, XB.Ht)
###################################################
### code chunk number 7: funwithfunload.Snw:313-415 (eval = FALSE)
###################################################
## fun.load.widals.ab <- function() {
##
## if( run.parallel ) {
## sfExport("Z", "XA.Hs", "XA.Ht", "XA.Hst.ls", "XB.Hs", "XB.Ht", "XB.Hst.ls",
## "locs", "lags", "b.lag", "cv", "rm.ndx", "train.rng", "test.rng", "xgeodesic",
## "ltco", "stnd.d")
## suppressWarnings(sfLibrary(widals))
## }
##
## if( length(lags) == 1 & lags[1] == 0 ) {
## p.ndx.ls <- list( c(1,2), c(3,4), c(5,7) )
## } else {
## p.ndx.ls <- list( c(1,2), c(3,4), c(5,6,7) )
## }
## assign( "p.ndx.ls", p.ndx.ls, pos=globalenv() )
##
## f.d <- list( dlog.norm, dlog.norm, dlog.norm, dlog.norm, dlog.norm,
## dlog.norm, dlog.norm )
## assign( "f.d", f.d, pos=globalenv() )
##
## FUN.MH <- function(jj, GP.mx, X) {
##
## if(cv==2) { ZhalsA <- Hals.fastcv.snow(jj, rm.ndx, Z, XA.Hs, XA.Ht, XA.Hst.ls, GP.mx) }
## if(cv==-2) { ZhalsA <- Hals.snow(jj, Z, XA.Hs, XA.Ht, XA.Hst.ls, b.lag, GP.mx) }
## Z.resids.A <- Z - ZhalsA
##
## Z.wid <- widals.snow(jj, rm.ndx=rm.ndx, Z=Z.resids.A, Hs=XB.Hs, Ht=XB.Ht, Hst.ls=XB.Hst.ls,
## locs=locs, lags=lags, b.lag=b.lag, cv=cv, geodesic=xgeodesic,
## wrap.around=NULL, GP.mx[ , c(3:7), drop=FALSE], stnd.d=stnd.d, ltco=ltco)
##
## Z.wid <- Z.wid + ZhalsA
##
## if( min(Z, na.rm=TRUE) >= 0 ) { Z.wid[ Z.wid < 0 ] <- 0 } ####### DZ EDIT
##
## Z.wid <- Z.clean.up(Z.wid)
##
## resids <- Z[ , unlist(rm.ndx)] - Z.wid[ , unlist(rm.ndx)]
## our.cost <- sqrt( mean( resids[ train.rng, ]^2 ) )
##
## if( is.nan(our.cost) ) { our.cost <- Inf }
##
## return( our.cost )
## }
## assign( "FUN.MH", FUN.MH, pos=globalenv() )
##
## #FUN.GP <- NULL
## FUN.GP <- function(GP.mx) {
## GP.mx[ GP.mx[ , 1] > rho.upper.limit, 1 ] <- rho.upper.limit
## GP.mx[ GP.mx[ , 2] < rgr.lower.limit, 2 ] <- rgr.lower.limit
## GP.mx[ GP.mx[ , 2] > rgr.upper.limit, 2 ] <- rgr.upper.limit
##
## GP.mx[ GP.mx[ , 3] > rho.upper.limit, 3 ] <- rho.upper.limit
## GP.mx[ GP.mx[ , 4] < rgr.lower.limit, 4 ] <- rgr.lower.limit
## GP.mx[ GP.mx[ , 4] > rgr.upper.limit, 4 ] <- rgr.upper.limit
##
## GP.mx[ GP.mx[ , 5] < d.alpha.lower.limit, 5 ] <- d.alpha.lower.limit
## xperm <- order(GP.mx[ , 5, drop=FALSE])
## GP.mx <- GP.mx[ xperm, , drop=FALSE]
## return(GP.mx)
## }
## assign( "FUN.GP", FUN.GP, pos=globalenv() )
##
## FUN.I <- function(envmh, X) {
## cat( "Improvement ---> ", envmh$current.best, " ---- " , envmh$GP, "\n" )
## }
## assign( "FUN.I", FUN.I, pos=globalenv() )
##
## FUN.EXIT <- function(envmh, X) {
##
## GP.mx <- matrix(envmh$GP, 1, length(envmh$GP))
##
## if(cv==2) { ZhalsA <- Hals.fastcv.snow(1, rm.ndx, Z, XA.Hs, XA.Ht, XA.Hst.ls, GP.mx) }
## if(cv==-2) { ZhalsA <- Hals.snow(1, Z, XA.Hs, XA.Ht, XA.Hst.ls, b.lag, GP.mx) }
##
## Z.resids.A <- Z - ZhalsA
##
## Z.wid <- widals.snow(1, rm.ndx=rm.ndx, Z=Z.resids.A, Hs=XB.Hs, Ht=XB.Ht, Hst.ls=XB.Hst.ls,
## locs=locs, lags=lags, b.lag=b.lag, cv=cv, geodesic=xgeodesic,
## wrap.around=NULL, GP.mx[ , c(3:7), drop=FALSE], stnd.d=stnd.d, ltco=ltco)
##
## Z.wid <- Z.wid + ZhalsA
##
## if( min(Z, na.rm=TRUE) >= 0 ) { Z.wid[ Z.wid < 0 ] <- 0 } ############ DZ EDIT
##
## assign( "Z.wid", Z.wid, envir=globalenv() )
##
## Z.wid <- Z.clean.up(Z.wid)
##
## resids <- Z[ , unlist(rm.ndx)] - Z.wid[ , unlist(rm.ndx)]
## our.cost <- sqrt( mean( resids[ test.rng, ]^2 ) )
##
## if( is.nan(our.cost) ) { our.cost <- Inf }
##
## cat( envmh$GP, " -- ", our.cost, "\n" )
##
## assign( "our.cost", our.cost, pos=globalenv() )
## assign( "GP", envmh$GP, pos=globalenv() )
## cat( paste( "GP <- c(", paste(format(GP,digits=5), collapse=", "), ") ### ",
## format(our.cost, width=6), "\n", sep="" ) )
## }
## assign( "FUN.EXIT", FUN.EXIT, pos=globalenv() )
## }
###################################################
### code chunk number 8: funwithfunload.Snw:423-449 (eval = FALSE)
###################################################
## GP <- c(1/10, 1, 1/10, 1, 5, 3, 1)
## sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
## ltco <- -10
## stnd.d <- TRUE
##
## rm.ndx <- I(1:n)
## cv <- -2
## lags <- c(0)
## b.lag <- -1
##
## d.alpha.lower.limit <- 0
## rho.upper.limit <- 100
## rgr.lower.limit <- 10^(-7)
## rgr.upper.limit <- 500
##
## FUN.GP <- NULL
##
## sfInit(TRUE, k.cpus)
## FUN.source <- fun.load.widals.ab
## FUN.source()
##
## set.seed(9999)
## MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
## k.glob, k.loc.coef=7, X = NULL)
## sfStop()
## #### 11.5234
###################################################
### code chunk number 9: funwithfunload.Snw:456-481 (eval = FALSE)
###################################################
## GP <- c(1/10, 1, 1/10, 1, 0.5, 3, 1)
## sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
## ltco <- -10
## stnd.d <- TRUE
##
## rm.ndx <- create.rm.ndx.ls(n, 14)
## cv <- 2
## lags <- c(0)
## b.lag <- 0
##
## d.alpha.lower.limit <- 0
## rho.upper.limit <- 100
## rgr.lower.limit <- 10^(-7)
## rgr.upper.limit <- 500
##
## FUN.GP <- NULL
##
## sfInit(TRUE, k.cpus)
## FUN.source <- fun.load.widals.ab
## FUN.source()
##
## set.seed(9999)
## MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
## k.glob, k.loc.coef=9, X = NULL)
## sfStop()
###################################################
### code chunk number 10: funwithfunload.Snw:509-560 (eval = FALSE)
###################################################
##
## options(stringsAsFactors=FALSE)
##
## k.cpus <- 2 #### set the number of cpus for snowfall
##
##
## library(widals)
## tau <- 210
## n.all <- 300
##
## set.seed(77777)
## locs.all <- cbind(runif(n.all), runif(n.all))
##
## D.mx <- distance(locs.all, locs.all, FALSE)
##
## Q <- 0.03*exp(-2*D.mx)
## F <- 0.99
## R <- diag(1, n.all)
## beta0 <- rep(0, n.all)
## H <- diag(1, n.all)
##
## xsssim <- SS.sim(F, H, Q, R, length.out=tau, beta0=beta0)
## Y1 <- xsssim$Y
##
##
##
## Hst.ss <- list()
## for(tt in 1:tau) {
## Hst.ss[[tt]] <- cbind( rep(sin(tt*2*pi/tau), n.all), rep(cos(tt*2*pi/tau), n.all) )
## colnames(Hst.ss[[tt]]) <- c("sinet", "cosinet")
## }
## Ht.original <- cbind( sin((1:tau)*2*pi/tau), cos((1:tau)*2*pi/tau) )
##
## Q2 <- diag(0.03, ncol(Hst.ss[[1]]))
## F2 <- 0.99
## beta20 <- rep(0, ncol(Hst.ss[[1]]))
## R2 <- 1*exp(-3*D.mx) + diag(0.001, n.all)
##
## xsssim2 <- SS.sim.tv(F2, Hst.ss, Q2, R, length.out=tau, beta0=beta20)
## Z2 <- xsssim2$Z
##
##
## Z.all <- Y1 + Z2
##
##
## #################### plot
## z.min <- min(Z.all)
## for(tt in 1:tau) {
## plot(locs.all, cex=(Z.all[ tt, ]-z.min)*0.3, main=tt)
## Sys.sleep(0.1)
## }
###################################################
### code chunk number 11: funwithfunload.Snw:567-608 (eval = FALSE)
###################################################
## train.rng <- 30:tau
## test.rng <- train.rng
##
##
## xgeodesic <- FALSE
## Z <- Z.all
## locs <- locs.all
## n <- n.all
## Ht <- Ht.original
## Hs <- matrix(1, nrow=n)
## Hst.ls <- NULL
##
##
## rm.ndx <- create.rm.ndx.ls(n, 14)
## k.glob <- 10
## run.parallel <- TRUE
##
## FUN.source <- fun.load.widals.a
##
## d.alpha.lower.limit <- 0
## rho.upper.limit <- 100
## rgr.lower.limit <- 10^(-7)
##
## GP <- c(1/10, 1, 0.01, 3, 1)
## cv <- 2
## lags <- c(0)
## b.lag <- 0
##
## sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
## ltco <- -10
## stnd.d <- TRUE
##
## FUN.GP <- NULL
##
## sfInit(TRUE, k.cpus)
## FUN.source()
##
## set.seed(99999)
## MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
## k.glob, k.loc.coef=7, X = NULL)
## sfStop()
###################################################
### code chunk number 12: funwithfunload.Snw:620-673 (eval = FALSE)
###################################################
## library(LatticeKrig)
##
## xxb <- 7
## yyb <- 7
## center <- as.matrix(expand.grid( seq( 0, 1, length=xxb), seq( 0, 1, length=yyb)))
##
## ###### run together
## ffunit <- function(x) { return( (x-min(x)) / (max(x)-min(x)) ) }
## locs.unit <- apply(locs, 2, ffunit)
## locs.unit <- matrix(as.vector(locs.unit), ncol=2)
## ###### run togther
##
## xPHI <- Radial.basis(as.matrix(locs.unit), center, 0.5)
## Hs.lkrig <- matrix(NA, nrow(locs), xxb*yyb)
## for(i in 1:nrow(locs)) {
## Hs.lkrig[i, ] <- xPHI[i]
## }
##
## XA.Hs <- Hs
## XA.Ht <- Ht.original
## XA.Hst.ls <- NULL
##
## Hst.sumup(XA.Hst.ls, XA.Hs, XA.Ht)
##
## XB.Hs <- 10*Hs.lkrig
## XB.Ht <- NULL
## XB.Hst.ls <- NULL
##
## Hst.sumup(XB.Hst.ls, XB.Hs, XB.Ht)
##
## GP <- c(1/10, 1, 1/10, 1, 5, 3, 1)
## sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
##
## rm.ndx <- create.rm.ndx.ls(n, 14)
## cv <- 2
## lags <- c(0)
## b.lag <- 0
##
## d.alpha.lower.limit <- 0
## rho.upper.limit <- 100
## rgr.lower.limit <- 10^(-7)
## rgr.upper.limit <- 100
##
## FUN.GP <- NULL
##
## sfInit(TRUE, k.cpus)
## FUN.source <- fun.load.widals.ab
## FUN.source()
##
## set.seed(9999)
## MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
## k.glob, k.loc.coef=7, X = NULL)
## sfStop()
|
/scratch/gouwar.j/cran-all/cranData/widals/inst/doc/funwithfunload.R
|
### R code from vignette source 'widals.Snw'
###################################################
### code chunk number 1: widals.Snw:151-154
###################################################
options(width=49)
options(prompt=" ")
options(continue=" ")
###################################################
### code chunk number 2: b1
###################################################
options(stringsAsFactors=FALSE)
library(snowfall)
k.cpus <- 2 #### set the number of cpus for snowfall
library(widals)
data(O3)
Z.all <- as.matrix(O3$Z)[366:730, ]
locs.all <- O3$locs[ , c(2,1)]
hsa.all <- O3$helevs
xdate <- rownames(Z.all)
tau <- nrow(Z.all)
n.all <- ncol(Z.all)
xgeodesic <- TRUE
###################################################
### code chunk number 3: b2
###################################################
Z <- Z.all
locs <- locs.all
n <- n.all
dateDate <- strptime(xdate, "%Y%m%d")
doy <- as.integer(format(dateDate, "%j"))
Ht <- cbind( sin(2*pi*doy/365), cos(2*pi*doy/365) )
Hs.all <- matrix(1, nrow=n.all)
Hst.ls.all <- NULL
Hs <- Hs.all
Hst.ls <- Hst.ls.all
Ht.original <- Ht
##########################
rm.ndx <- create.rm.ndx.ls(n, 14)
b.lag <- 0
train.rng <- 30:tau
test.rng <- train.rng
GP <- c(1/10, 1)
k.glob <- 9
rho.upper.limit <- 100
rgr.lower.limit <- 10^(-7)
sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
run.parallel <- TRUE
sfInit(TRUE, k.cpus)
FUN.source <- fun.load.hals.a
FUN.source()
MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
k.glob, k.loc.coef=7, X = NULL)
sfStop()
###################################################
### code chunk number 4: a2
###################################################
Z.als <- Hals.snow(1, Z = Z, Hs = Hs, Ht = Ht, Hst.ls = Hst.ls,
b.lag = b.lag, GP.mx = matrix(GP, 1, 2))
resids <- Z-Z.als
sqrt( mean( resids[test.rng, ]^2 ) )
###################################################
### code chunk number 5: a3
###################################################
Hs.all <- cbind(matrix(1, nrow=n.all), hsa.all)
Hs <- Hs.all
GP <- c(1/10, 1)
sfInit(TRUE, k.cpus)
MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
k.glob, k.loc.coef=7, X = NULL)
sfStop()
###################################################
### code chunk number 6: a4
###################################################
Hst.ls.all <- H.Earth.solar(locs[ , 2], locs[ , 1], dateDate)
Hst.ls <- Hst.ls.all
GP <- c(1/10, 1)
sfInit(TRUE, k.cpus)
MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
k.glob, k.loc.coef=7, X = NULL)
sfStop()
###################################################
### code chunk number 7: a5
###################################################
Hst.ls.all2 <- list()
for(tt in 1:tau) {
Hst.ls.all2[[tt]] <- cbind(Hst.ls.all[[tt]], Hst.ls.all[[tt]]*hsa.all)
colnames(Hst.ls.all2[[tt]]) <- c("ISA", "ISAxElev")
}
Hst.ls <- Hst.ls.all2
GP <- c(1/10, 1)
sfInit(TRUE, k.cpus)
MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
k.glob, k.loc.coef=7, X = NULL)
sfStop()
###################################################
### code chunk number 8: a6
###################################################
Hals.ses(Z, Hs, Ht, Hst.ls, GP[1], GP[2], b.lag, test.rng)
###################################################
### code chunk number 9: a7
###################################################
Z <- Z.all
Hst.ls <- stnd.Hst.ls(Hst.ls.all2)$sHst.ls
Hs <- stnd.Hs(Hs.all)$sHs
Ht <- stnd.Ht(Ht, nrow(Hs))
GP <- c(1/10, 1)
sfInit(TRUE, k.cpus)
MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
k.glob, k.loc.coef=7, X = NULL)
sfStop()
###################################################
### code chunk number 10: a8
###################################################
z.mean <- mean(Z.all)
z.sd <- sd(as.vector(Z.all))
Z <- (Z.all - z.mean) / z.sd
GP <- c(1/10, 1)
sfInit(TRUE, k.cpus)
MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
k.glob, k.loc.coef=7, X = NULL)
sfStop()
our.cost * z.sd
###################################################
### code chunk number 11: a9 (eval = FALSE)
###################################################
##
## Z <- Z.all
## Hst.ls <- Hst.ls.all2
## Hs <- Hs.all
## Ht <- Ht.original
##
## FUN.source <- fun.load.widals.a
##
## d.alpha.lower.limit <- 0
##
## GP <- c(1/1000, 1, 0.01, 3, 1)
## cv <- 2
## lags <- c(0)
## b.lag <- 0
##
## sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
## ltco <- -10
## stnd.d <- TRUE
##
## sfInit(TRUE, k.cpus)
## FUN.source()
##
## MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
## k.glob, k.loc.coef=7, X = NULL)
## sfStop()
##
###################################################
### code chunk number 12: a10
###################################################
rm.ndx <- 1:n
Z <- Z.all
Hst.ls <- Hst.ls.all2
Hs <- Hs.all
Ht <- Ht.original
FUN.source <- fun.load.widals.a
d.alpha.lower.limit <- 0
GP <- c(1/1000, 1, 0.01, 3, 1)
cv <- -2
lags <- c(0)
b.lag <- -1
sds.mx <- seq(2, 0.01, length=k.glob) * matrix(1, k.glob, length(GP))
ltco <- -10
stnd.d <- TRUE
sfInit(TRUE, k.cpus)
FUN.source()
MSS.snow(FUN.source, NA, p.ndx.ls, f.d, sds.mx=sds.mx,
k.glob, k.loc.coef=7, X = NULL)
sfStop()
###################################################
### code chunk number 13: a10
###################################################
Hals.ses(Z, Hs, Ht, Hst.ls, GP[1], GP[2], b.lag, test.rng)
###################################################
### code chunk number 14: a11
###################################################
Z <- Z.all
Hst.ls <- Hst.ls.all2
Hs <- Hs.all
Ht <- Ht.original
Hs0 <- cbind(matrix(1, length(O3$helevs0)), O3$helevs0)
Hst0isa.ls <- H.Earth.solar(O3$locs0[ , 1], O3$locs0[ , 2], dateDate)
Hst0.ls <- list()
for(tt in 1:tau) {
Hst0.ls[[tt]] <- cbind(Hst0isa.ls[[tt]], Hst0isa.ls[[tt]]*O3$helevs0)
colnames(Hst0.ls[[tt]]) <- c("ISA", "ISAxElev")
}
locs0 <- O3$locs0[ , c(2,1)]
Z0.hat <- widals.predict(Z, Hs, Ht, Hst.ls, locs, lags, b.lag, Hs0, Hst0.ls,
locs0=locs0, geodesic=xgeodesic, wrap.around=NULL, GP, stnd.d, ltco)[10:tau, ]
ydate <- xdate[10:tau]
#xcol.vec <- heat.colors(max(round(Z0.hat)))
#xcol.vec <- rev(rainbow(max(round(Z0.hat))))
xcol.vec <- rev(rainbow(630)[1:max(round(Z0.hat))])
xleg.vals <- round( seq(1, max(Z0.hat)-1, length=(5)) / 1 ) * 1
xleg.cols <- xcol.vec[xleg.vals+1]
###################################################
### code chunk number 15: a11 (eval = FALSE)
###################################################
## for(tt in 1:nrow(Z0.hat)) {
## plot(0, 0, xlim=c(-124.1, -113.9), ylim=c(32.5, 42), type="n", main=ydate[tt])
## ## points(locs0[ , c(2,1)], cex=Z0.hat[tt,] / 30) ## uncomment to see sites
## this.zvec <- round(Z0.hat[tt,])
## this.zvec[ this.zvec < 1] <- 1
## this.color <- xcol.vec[ this.zvec ]
## points(locs0[ , c(2,1)], cex=1.14, col=this.color, pch=19 )
## #points(locs[ , c(2,1)], cex=Z[tt,] / 30, col="red")
## legend(-116, 40, legend=rev(xleg.vals), fill=FALSE, col=rev(xleg.cols),
## border=NA, bty="n", text.col=rev(xleg.cols))
## Sys.sleep(0.1)
## }
###################################################
### code chunk number 16: widals.Snw:511-523
###################################################
ydate <- xdate[10:tau]
tt <- 180
plot(0, 0, xlim=c(-124.1, -113.9), ylim=c(32.5, 42), type="n", main=ydate[tt],
xlab="", ylab="")
## points(locs0[ , c(2,1)], cex=Z0.hat[tt,] / 30) ## uncomment to see sites
this.zvec <- round(Z0.hat[tt,])
this.zvec[ this.zvec < 1] <- 1
this.color <- xcol.vec[ this.zvec ]
points(locs0[ , c(2,1)], cex=1.14, col=this.color, pch=19 )
#points(locs[ , c(2,1)], cex=Z[tt,] / 30, col="red")
legend(-116, 40, legend=rev(xleg.vals), fill=FALSE, col=rev(xleg.cols), border=NA,
bty="n", text.col=rev(xleg.cols))
|
/scratch/gouwar.j/cran-all/cranData/widals/inst/doc/widals.R
|
knit_print.widgetframe <- function(x, ..., options = NULL) {
# Knit child widget
childWidget <- attr(x$x,'widget')
# Use the chunk label if available for enclosed widget's HTML file name
if (!is.null(options) && !is.null(options$label)) {
# TODO We may need to sanitize options$label
childFile <- paste0('widget_',options$label,'.html')
} else {
childFile <- paste0(basename(tempfile('widget_', '.')),'.html')
}
# Should the widget be self_contained HTML i.e. deps inlined?
selfContained <- FALSE
if (!is.null(options) && !is.null(options$widgetframe_self_contained) &&
options$widgetframe_self_contained == TRUE) {
selfContained <- TRUE
}
# Should dependencies of widgets of different types be isolated?
# This has no effect if selfContained = TRUE as in that case the deps are inlined.
isolateWidgets <- TRUE
if (!is.null(options) && !is.null(options$widgetframe_isolate_widgets) &&
options$widgetframe_isolate_widgets == FALSE) {
isolateWidgets <- FALSE
}
# Hack-ish way to get dependencies folder for the parent document.
# See https://github.com/yihui/knitr/issues/1390
defWidgetsDir <- file.path(knitr::opts_chunk$get('fig.path'), 'widgets')
widgetsDir <- NULL
if (!is.null(options) && !is.null(options$widgetframe_widgets_dir)) {
widgetsDir <- options$widgetframe_widgets_dir
}
# We need a widgetsdir if not self_contained
if(!selfContained && is.null(widgetsDir)) {
widgetsDir <- defWidgetsDir
}
# Place child widget inside `widgetsDir` if provided
if(!is.null(widgetsDir)) {
if(!dir.exists(widgetsDir)) {
dir.create(widgetsDir, recursive = TRUE)
}
oldwd <- setwd(widgetsDir)
on.exit(setwd(oldwd), add = TRUE)
}
if (file.exists(childFile)) {
unlink(childFile, force = TRUE)
}
# Directory where to put child widget's dependencies.
childWidgetLibs <- 'libs'
# If widget dependencis should be isolated by widget type, place each widget type's
# dependencies in seperate folder.
# This allows mixing widgets dependent on different versions of the same JS/CSS libs.
if(isolateWidgets) {
widgetClass <- class(childWidget)[[1]]
childWidgetLibs <- paste0(widgetClass,'_libs')
}
htmlwidgets::saveWidget(childWidget, childFile, knitrOptions = options,
libdir = childWidgetLibs, selfcontained = selfContained)
# go back up since we decended into the child widget dir.
if(!is.null(widgetsDir)) {
setwd(oldwd)
}
# Point parent widget to proper path of child widget's HTML
if(is.null(widgetsDir)) {
x$x$url <- childFile
# Below is a hack for bookdown to pick up dependencies
# See https://github.com/rstudio/bookdown/issues/271
x <- x %>%
htmlwidgets::appendContent(
htmltools::HTML(sprintf("<!-- widgetframe widget-href=\"%s\" -->", childFile)))
} else {
x$x$url <- file.path(widgetsDir,childFile)
}
# Knit parent widget
NextMethod()
}
# Register the knitr_print.widgetframe as a Method of the knit_print generic.
# Shamelessly copied from htmlwidget code.
.onLoad <- function(...) {
pkg <- 'knitr'
generic <- 'knit_print'
class <- 'widgetframe'
func <- get('knit_print.widgetframe')
if (pkg %in% loadedNamespaces()) {
registerS3method(generic, class, func, envir = asNamespace(pkg))
}
setHook(
packageEvent(pkg, "onLoad"),
function(...) {
registerS3method(generic, class, func, envir = asNamespace(pkg))
}
)
}
|
/scratch/gouwar.j/cran-all/cranData/widgetframe/R/knitr_support.R
|
#' widgetframe: A package for wrapping htmlwidgets in responsive iframes.
#'
#' This package provides two functions \code{\link{frameableWidget}}, and \code{\link{frameWidget}}.
#' The \code{\link{frameableWidget}} is used to add extra code to a htmlwidget which
#' allows is to be rendered correctly inside a responsive iframe.
#' The \code{\link{frameWidget}} is a htmlwidget which displays content of another
#' htmlwidget inside a responsive iframe.
#'
#' @importFrom magrittr %>%
#'
#' @name widgetframe
#' @docType package
NULL
|
/scratch/gouwar.j/cran-all/cranData/widgetframe/R/widgetframe-package.r
|
pymjsDependency <- function() {
list(
htmltools::htmlDependency(
name = 'pymjs', version = '1.3.2',
src = system.file('htmlwidgets/pymjs', package = 'widgetframe'),
script = c('pym.v1.min.js')
)
)
}
addPymjsDependency <- function(widget) {
widget$dependencies <- c(pymjsDependency(), widget$dependencies)
widget
}
blazyDependency <- function() {
list(
htmltools::htmlDependency(
name = 'blazy', version = '1.8.2',
src = system.file('htmlwidgets/blazy', package = 'widgetframe'),
script = c('blazy.min.js')
)
)
}
addBlazyDependency <- function(widget) {
widget$dependencies <- c(blazyDependency(), widget$dependencies)
widget
}
#' Options for widget's iframe.
#' @description Taken from \href{http://blog.apps.npr.org/pym.js/api/pym.js/1.3.1/module-pym.Parent.html}{Pym.js Documentation}.
#' In addition also check out the \href{https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe}{iframe documentation}.
#' @param xdomain xdomain to validate messages received.
#' @param title If passed it will be assigned to the iframe title attribute.
#' @param name If passed it will be assigned to the iframe name attribute.
#' @param id If passed it will be assigned to the iframe id attribute.
#' @param allowfullscreen If TRUE it will set the iframe allowfullscreen attribute to true.
#' @param sandbox If passed it will be assigned to the iframe sandbox attribute.
#' @param lazyload If TRUE the child widget is lazy loaded using \href{http://dinbror.dk/blog/blazy/?ref=github#iframe}{bLazy.js}.
#' @export
frameOptions <- function(xdomain = '*', title=NULL, name=NULL,
id = NULL, allowfullscreen=FALSE,
sandbox=NULL, lazyload = FALSE) {
purrr::keep(
list(
xdomain = xdomain,
title = title,
name = name,
id = id,
allowfullscreen = allowfullscreen,
sandbox = sandbox,
lazyload = lazyload
), ~!is.null(.))
}
#' @title Adds pymjs initialization code to a htmlwidget.
#' @description
#' This function augments a htmlwidget so that when saved,
#' the resulting HTML document can be rendered correctly inside a responsive iframe
#' (created using \href{http://blog.apps.npr.org/pym.js/}{Pym.js}) of another HTML document.
#' @details
#' Generate your htmlwidget in the normal way and then call this function
#' passing in your widget. Then call \code{\link[htmlwidgets]{saveWidget}()} and
#' the saved HTML file is now embeddable inside a Pym.js iframe of another HTML document.
#' See \href{http://blog.apps.npr.org/pym.js/}{Pym.js} documentation on how to
#' create an HTML document with a responsive iframe.
#' @param widget The widget to add the pymjs code to.
#' @param renderCallback An optional Javascript function wrapped in \code{\link[htmlwidgets]{JS}()}
#' which will be called when parent sends a resize event.
#' @examples \dontrun{
#' library(leaflet)
#' l <- leaflet() %>% addTiles() %>% setView(0,0,1)
#' htmlwidgets::saveWidget(
#' widgetframe::frameableWidget(l),'some-directory-on-your-disk')
#' }
#' @seealso \code{\link{frameWidget}()}.
#' @export
frameableWidget <- function(widget, renderCallback = NULL) {
if (!("htmlwidget" %in% class(widget))) {
stop ("The input widget argument is not a htmldidget.")
}
if ("widgetframe" %in% class(widget)) {
stop ("Can't make an already framed widget frameable.")
}
# is it already frameable
if ('frameablewidget' %in% class(widget)) {
return(widget)
}
# Add 'frameablewidget' to the class list of this widget at the last but one position
numClasses <- length(class(widget))
class(widget) <- c(class(widget)[1:(numClasses-1)],
'frameablewidget', class(widget)[[numClasses]])
# Padding throws off pym.js calculations
widget$sizingPolicy$padding <- 0
widget$sizingPolicy$viewer$padding <- 0
widget$sizingPolicy$browser$padding <- 0
initChildJsCode <- NULL
if (is.null(renderCallback)) {
initChildJsCode <- "HTMLWidgets.pymChild = new pym.Child();"
} else {
initChildJsCode <- sprintf(
"HTMLWidgets.pymChild = new pym.Child({renderCallback : %s});", renderCallback)
}
# Send the child widget's height after a small delay to the parent.
# This is necessary to correctly initialize the height of the iframe for various kinds of widgets.
initChildJsCode <- paste0(initChildJsCode,
"HTMLWidgets.addPostRenderHandler(function(){
setTimeout(function(){HTMLWidgets.pymChild.sendHeight();},100);
});")
widget %>%
addPymjsDependency() %>%
htmlwidgets::appendContent(htmltools::tags$script(initChildJsCode))
}
#' @title A widget that wraps another widget inside a responsive iframe.
#' @description
#' Uses \href{http://blog.apps.npr.org/pym.js/}{Pym.js}.
#' Pym.js embeds and resizes an iframe responsively (width and height) within
#' its parent container. It also bypasses the usual cross-domain issues.
#'
#' @details
#' This widget can be used in places where a HTML page's CSS rules or Javascript code
#' can cause issues in a widget. Wrapping your widgets this way allows for the widget
#' code to be unaffected by the parent HTML's CSS/JS. The target widget is
#' conveniently displaed in a responsive iframe and not subject to parent HTML's CSS/JS.
#'
#' @param targetWidget The widget to embed inside an iframe.
#' @param width Defaults to 100%. You can either specify '10%', '50%' etc. or
#' 100, 200 (in pixel). This will override the width of the enclosed widget.
#' @param height Defaults to NULL. You can either specify '10%', '50%' etc. or
#' 100, 200 (in pixel). This will override the height of the enclosed widget.
#' @param elementId The element ID of the parent widget.
#' @param options Options for the iframe.
#'
#' @import htmlwidgets
#' @examples \dontrun{
#' l <- leaflet() %>% addTiles() %>% setView(0,0,1)
#' frameWidget(l)
#' }
#'
#' @seealso \code{\link{frameOptions}()}.
#' @export
frameWidget <- function(targetWidget, width = '100%', height = NULL, elementId = NULL,
options = frameOptions()) {
# Safety check for accidental frameWidget(frameWidget(someWidget))
if ('widgetframe' %in% class(targetWidget)) {
warning("Re-framing an already framed widget with new params")
targetWidget <- attr(targetWidget$x,'widget')
}
## Add Pym.js init code to the target widget if not already done so.
targetWidget <- frameableWidget(targetWidget)
# Override targetWidget's width/height by this widget's width/height if provided.
# Alternatively use target widget's width/height if none provided for the framing widget.
if (!is.null(width)) {
targetWidget$width <- width
} else {
if (!is.null(targetWidget$width)) {
width <- targetWidget$width
}
}
if (!is.null(height)) {
targetWidget$height <- height
} else {
if (!is.null(targetWidget$height)) {
height <- targetWidget$height
}
}
widgetData = structure(
list(
url = 'about:blank', # this will be overwritten when the widget is rendered
options = options
), widget = targetWidget )
# create widget
widget <- htmlwidgets::createWidget(
name = 'widgetframe',
x = widgetData,
width = width,
height = height,
package = 'widgetframe',
elementId = elementId
)
if(!is.null(options) && options$lazyload) {
widget <- widget %>%
addBlazyDependency() %>%
htmlwidgets::appendContent(htmltools::tags$script("if(!window.bLazy){window.bLazy = new Blazy();}"))
}
widget
}
#' @export
print.widgetframe <- function(x, ..., view = interactive()) {
# Should we use RStudio's viewer or simply open in a browser.
viewer <- getOption("viewer", utils::browseURL)
# This will be where parent widget's HTML will be written
parentDir <- tempfile('widgetframe')
dir.create(parentDir)
childWidget <- attr(x$x,'widget')
# This is just an extra safety check, there is no reason why the childWidget should be null.
if (!is.null(childWidget)) {
childDir <- file.path(parentDir,'widget')
dir.create(childDir)
childHTML <- file.path(childDir, "index.html")
# Save child widget's HTML inside '/widget' folder inside parent widget's HTML folder.
htmltools::save_html(
htmltools::as.tags(childWidget, standalone = TRUE), file = childHTML)
# Set the relative URL for child HTML
x$x$url <- './widget/index.html'
}
# Save parent widget's HTML
parentHTML <- file.path(parentDir,'index.html')
htmltools::save_html(
htmltools::as.tags(x, standalone = TRUE), file = parentHTML)
if (view) {
viewer(parentHTML)
}
invisible(x)
}
#' Save a widgetframe and its child widget to HTML files.
#'
#' @description Similar to \code{\link[htmlwidgets]{saveWidget}()} with the addition
#' that both the parent widget and the enclosed child widget are saved to two different HTML files.
#'
#' @param widget widgetframe to save
#' @param file File to save the parent widget into. The child widget will be saved to
#' `basename(file)_widget/index.html`.
#' @param selfcontained Whether to save the parent and child HTMLs as a single self-contained files.
#' WARNING: Setting this option to true will still result in two HTMLs, one for
#' the parent and another for the child widget (with external resources base64 encoded),
#' or files with external resources placed in an adjacent directory.
#' @param libdir Directory to copy HTML dependencies into (defaults to
#' filename_files).
#' @param background Text string giving the html background color of the widget.
#' Defaults to white.
#' @param knitrOptions A list of \pkg{knitr} chunk options.
#' @export
saveWidgetframe <- function(widget, file, selfcontained = FALSE,
libdir = NULL,
background = "white", knitrOptions = list()) {
parentWidget <- NULL
if ('widgetframe' %in% class(widget)) {
parentWidget <- widget
} else {
parentWidget <- frameWidget(widget)
}
childDir <- file.path(
dirname(file),
paste0(tools::file_path_sans_ext(basename(file)),'_widget'))
dir.create(childDir)
parentWidget$x$url <- paste0(
tools::file_path_sans_ext(basename(file)),'_widget/index.html')
childWidget <- attr(parentWidget$x,'widget')
oldwd <- setwd(childDir)
htmlwidgets::saveWidget(childWidget, 'index.html', selfcontained = selfcontained,
libdir = libdir, background = background,
knitrOptions = knitrOptions)
setwd(oldwd)
htmlwidgets::saveWidget(parentWidget, file, selfcontained = selfcontained,
libdir = libdir, background = background,
knitrOptions = knitrOptions)
}
#' Shiny bindings for widgetframe
#'
#' Output and render functions for using widgetframe within Shiny
#' applications and interactive Rmd documents.
#'
#' @param outputId output variable to read from
#' @param width,height Must be a valid CSS unit (like \code{'100\%'},
#' \code{'400px'}, \code{'auto'}) or a number, which will be coerced to a
#' string and have \code{'px'} appended.
#' @param expr An expression that generates a widgetframe
#' @param env The environment in which to evaluate \code{expr}.
#' @param quoted Is \code{expr} a quoted expression (with \code{quote()})? This
#' is useful if you want to save an expression in a variable.
#'
#' @name widgetframe-shiny
#'
#' @export
widgetframeOutput <- function(outputId, width = '100%', height = '400px'){
htmlwidgets::shinyWidgetOutput(outputId, 'widgetframe', width, height, package = 'widgetframe')
}
#' @rdname widgetframe-shiny
#' @export
renderWidgetframe <- function(expr, env = parent.frame(), quoted = FALSE) {
if (!quoted) { expr <- substitute(expr) } # force quoted
htmlwidgets::shinyRenderWidget(expr, widgetframeOutput, env, quoted = TRUE)
}
|
/scratch/gouwar.j/cran-all/cranData/widgetframe/R/widgetframe.R
|
## ---- eval=FALSE---------------------------------------------------------
# install.packages('widgetframe')
## ---- eval=FALSE---------------------------------------------------------
# if(!require(devtools)) {
# install.packages('devtools')
# }
# devtools::install_github('bhaskarvk/widgetframe')
## ---- eval=FALSE---------------------------------------------------------
# library(leaflet)
# library(widgetframe)
# l <- leaflet() %>% addTiles()
# htmlwidgets::saveWidget(frameableWidget(l),'leaflet.html')
|
/scratch/gouwar.j/cran-all/cranData/widgetframe/inst/doc/Using_widgetframe.R
|
---
title: "Using widgetframe"
author: "Bhaskar V. Karambelkar"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Using widgetframe}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
The `widgetframe` package eases embedding of `htmlwidgets` inside various HTML based R Markdown documents using iframes.
To make the iframes [responsive](https://en.wikipedia.org/wiki/Responsive_web_design) it uses NPR's [Pymjs](http://blog.apps.npr.org/pym.js/) library.
This package provides two primary functions, `frameableWidget`, and `frameWidget`. `frameableWidget` is used to add extra code to a `htmlwidgets` instance, which allows it to be rendered inside a responsive iframe. `frameWidget` returns a new `htmlwidgets` instance, which wraps and displays content of another `htmlwidgets` instance (e.g. `leaflet`, `DT` etc.) inside a responsive iframe.
### Current Status
For each of the document type below you can find fully working example code in the [Github Repo](https://github.com/bhaskarvk/widgetframe/tree/examples).
- Works With
* [Flex Dashboard](http://rmarkdown.rstudio.com/flexdashboard/): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/flexdashboard/dashboard.html).
* [RMarkdown](rmarkdown.rstudio.com) + [knitr](yihui.name/knitr/): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/rmarkdown/knitr_example.html).
* [RMarkdown Website](http://rmarkdown.rstudio.com/lesson-13.html): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/rmarkdown-website/site/index.html).
* [Xaringan Presentations](https://slides.yihui.name/xaringan/): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/xaringan/widgetframe.html#1).<br/>(May also work with other RMarkdown + knitr based presentations.)
* [Bookdown](https://bookdown.org/) gitbook: (Needs a Makefile for assembly). [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/bookdown/book/index.html).
* [blogdown](https://github.com/rstudio/blogdown/): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/blogdown/public/index.html).
<br/>
- Does not (yet) work with
* Shiny: See [Github Issue](https://github.com/bhaskarvk/widgetframe/issues/11)
* Crosstalk: See [Github Issue](https://github.com/bhaskarvk/widgetframe/issues/3)
### Installation
Avaliable on [CRAN](https://cran.r-project.org/package=widgetframe) and can be installed using ...
```{r, eval=FALSE}
install.packages('widgetframe')
```
Or install the dev version from Github using `devtools` ...
```{r, eval=FALSE}
if(!require(devtools)) {
install.packages('devtools')
}
devtools::install_github('bhaskarvk/widgetframe')
```
### Usage
#### `frameableWidget` function.
The `frameableWidget` function should be used when you need a HTML which can be embedded in an external CMS like WordPress or Blogger, or a static HTML website.
```{r, eval=FALSE}
library(leaflet)
library(widgetframe)
l <- leaflet() %>% addTiles()
htmlwidgets::saveWidget(frameableWidget(l),'leaflet.html')
```
The resulting `leaflet.html` file contains the necessary Pym.js Child initialization code and will work inside a regular iFrame or better yet a Pym.js responsive iFrame. It is expected that the site which is going to embed this widget's content has the necessary Pymjs Parent initialization code as described [here](http://blog.apps.npr.org/pym.js/). The HTML dependencies of the widget (CSS/JS files) will be either inlined or kept external depending on the `seflcontained` argument to `saveWidget`.
#### `frameWidget` function
`frameWidget` function takes an existing `htmlwidgets` instance such as `leaflet` or `DT` etc., wraps it and returns a new `htmlwidgets` instance, which when rendered, displays the input wrapped `htmlwdigets` instance inside a responsive iFrame. This function can be used to knit htmlwidgets such that they are unaffected by the parent HTML file's CSS. This could be useful in [bookdown](https://bookdown.org/) or [R Markdown Websites](http://rmarkdown.rstudio.com/rmarkdown_websites.html) to embed widgets such that they are unaffected by the site's global CSS/JS.
```
```{r}
library(leaflet)
library(widgetframe)
l <- leaflet(height=300) %>% addTiles() %>% setView(0,0,1)
frameWidget(l)
```
```
```
```{r}
library(dygraphs)
ts <- dygraph(nhtemp, main = “New Haven Temperatures”,
height=250, width=‘95%’)
frameWidget(ts)
```
```
To know more about how `widgetframe` and `knitr`/`rmarkdown` work together, see the [`widgetframe` and `knitr`](widgetframe_and_knitr.html) vignette.
|
/scratch/gouwar.j/cran-all/cranData/widgetframe/inst/doc/Using_widgetframe.Rmd
|
---
title: "widgetframe and knitr"
author: "Bhaskar V. Karambelkar"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{widgetframe and knitr}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## `knitr`
The [`knitr`](https://yihui.name/knitr/) package, along with the [`rmarkdown`](http://rmarkdown.rstudio.com/) package converts a R markdown (Rmd) document into a target document, which can be an HTML Document, a HTML Website, a Dashboard, or a PDF/Word Document etc.
`widgetframe` is designed to be used in Rmd documents which will eventually be knitted to an HTML or a derived format. There is little or no benefit in using `widgetframe::frameWidget()` when the output format is not HTML based such as PDF, Microsoft Word etc. In fact `widgetframe` will most definitely not work for such output formats.
## Regular `htmlwidgets` and `knitr`
By default when knitting `htmlwidgets` the `htmlwidgets:::knit_print.htmlwidgets()` function (an internal function exposed as an S3 method) is called. The output of this call is a `list` containing the HTML code + a list of HTML dependencies (JS/CSS) required to render the widget. How this is then inserted into the final document depends on the output format. For this discussion we are going to limit to HTML based output formats because as noted above `widgetframe` is designed to work only for HTML based output formats.
Let's start with the simplest of HTML output format `rmarkdown::html_document()`.
The `self_contained` (default = `TRUE`), and the `lib_dir` (default = name of document + `_files`)
arguments of this output format dictate how `htmlwidgets` instances appear in the final document. If `self_contained` is `TRUE` then the HTML dependencies (JS/CSS) are all inlined and the result is just one single HTML document. Naturally this document is quite large in size due to the dependencies being inlined. If `self_contained` is `FALSE` then the HTML dependencies are kept in a separate directory determined by the `lib_dir` argument. Other HTML based formats like `bookdown`, `flexdashboard` etc. too have similar arguments. This is not surprising as they tend to extend `rmarkdown::html_document`.
### Potential Issues
Unless you are working on small one-off Rmd document, it is never a good idea to have `self_contained` set to its default value `TRUE`. It results in large HTML documents which are slow to load in the browser. Secondly by inlining dependencies you lose the ability to share common dependencies across different HTMLs. Lastly you also limit the browser's ability to cache HTML dependencies across sessions.
Even if you were to externalize the dependencies by setting `sefl_contained=FALSE`, there are still two potential issues...
* Different `htmlwidgets` may depend on different versions of the same Javascript/CSS dependency. But when the final document is produced only a single version of the said dependency is used. This may cause certain widgets to not display, or work incorrectly.
* The styling rules (CSS) of the widget may be overridden by those of the output format. This will again result in the widget not displaying properly in the final document.
These problems typically don't occur when knitting one-off HTML documents using the `rmarkdown::html_document` format. But they do occur once you start outputting documents in the `bookdown`, `blogdown`, `rmarkdown` websites, `xaringan` and other HTML based output formats. And this is where `widgetframe` comes in.
## `widgetframe`
`widgetframe` is itself a `htmlwidgets` instance, but of a different kind. Instead of wrapping a Javascript based dataviz object, it wraps another `htmlwidgets` instance like `leaflet`, or `DT`, or `dygraphs` etc. It does so by embedding the target `htmlwidgets` instance in a HTML [iframe](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe). It also uses NPR's [pym.js](http://blog.apps.npr.org/pym.js/) Javascript library to make the iframes [responsive](https://en.wikipedia.org/wiki/Responsive_web_design). This allows you to easily embed `htmlwidgets` inside complex HTML documents and avoid the issues mentioned in the section above.
## `widgetframe` and `knitr`
To understand how the knitting of `widgetframe`s differ from regular `htmlwidgets`, let's examine the following code. It shows you how to use `widgetframe::fameWidget()` function in a RMarkdown document and the three knitr chunk options it supports.
```r
```{r, include=FALSE}
# widgetframe supports 3 custom knitr chunk options...
# For all practicle purposes this should always be FALSE
knitr::opts_chunk$set(widgetframe_self_contained = FALSE) # default = FALSE
# For all practicle purposes this should always be TRUE
knitr::opts_chunk$set(widgetframe_isolate_widgets = TRUE) # default = TRUE
# Only needed in bookdown format/s such as bookdown::gitbook. Otherwise don't set.
# knitr::opts_chunk$set(widgetframe_widgets_dir = 'widgets' )
```
```{r leaflet-01}
library(leaflet)
library(widgetframe)
l <- leaflet() %>% addTiles() %>% setView(0,0,1)
frameWidget(l, width='90%')
```
```
While using `wigdetframe` is as simple as `widgetframe::frameWidget(some_other_widget)`, how the widget is knitted depends on three custom knitr chunk options explained below. When `knitr` comes across a `widgetframe::frameWidget()` call in a R Markdown document, it calls `widgetframe:::knit_print.widgetframe()` function (internal function exposed as a S3 method) to render the widget. This function is a wrapper around the `htmlwidgets:::knit_print.htmlwidgets()` function of the taget `htmlwidgets` instance. It is important to know that both `knitr_print.widgetframe()` and `knitr_print.htmlwidgets()` functions have no way of knowing what the target output format is and what arguments were passed to the target output format. So in order to knit the target widget in a child HTML document, which is displayed inside an iframe of the parent HTML document, `widgetframe` needs to depend of the three chunk options shown in the code sample above. We now discuss these 3 options and what their values should be for different output formats.
### widgetfram_self_contained
This option is similar to the `self_contained` argument of the `rmarkdown::html_document()` output format. The reason we need a separate chucnk option is because ...
1. As explained above `knitr_print.widgetframe()` has no way of knowing what the output format is and what arguments were passed to it.
2. Unlike `self_contained` which defaults to `TRUE`, `widgetframe_self_contained` defaults to `FALSE`. That is to say that by default when using `widgetframe` the dependencies of the target `htmlwidgets` instance are kept in a separate directory.
There is very little reason to set this option to `TRUE`. If however you do set it to `TRUE` the HTML file for the wrapped widget will have its dependencies inlined, resulting in a single large HTML file. Note that this is not the same as your final output HTML. This is just the HTML for the widget which is displayed inside an iframe in the final HTML document.
Wheter the final HTML document has inlined dependencies depends on the `self_contaied` argument of your output format e.g. `rmarkdown::html_document()`.
### widgetframe_isolate_widgets
Defaults to `TRUE`, and when `TRUE`, isolates HTML dependencies (CSS/JS) of `htmlwidgets` of different types. This avoids compatibility issues when `htmlwidgets` of different types depend on the same dependency(ies) but on different versions. For example if you are using some `leaflet`, and some `DT` `htmlwdigets` in your document (doesn't matter how many), then the dependencies of `leaflet` widgets will be stored separately from dependencies of `DT` widgets and any other widget other than `leaflet`. So `leaflet` can depend on version 'X' of `jQuery` and `DT` can depend on version 'Y' and both will work correctly. Note that multiple widgets of the same type will share the same set of dependencies in order to avoid unnecessary duplication.
There is very little reason to set this option to `FALSE`.
### widgetframe_widgets_dir
This option, if provided, determines where the HTML code for the wrapped `htmlwidgets` instance is written. Before discussing more we should note that `knitr_print.htmlwidgets()` never actually creates any files/directories or touches the file-system in any way. It merely returns a R list which then used by the output format to embed the widget's HTML (and dependencies) in the final document. However, `knitr_print.widgetframe()` does create HTML file/s and dependencies directories for the wrapped widget. It needs to, so that the final document can embed the widget's HTML which is saved separately, inside an iframe. This may not be important to know from a user perspective but a must know, if you want to extend or contribute to `widgetframe`.
For almost all output formats except `bookdown`, this option should not be set and it will default to `file.path(knitr::opts_chunk$get('fig.path'),'widgets')`. That is a `widgets` directory inside the directory `knitr::opts_chunk$get('fig.path')`. This is done this way because as noted `knitr_print` has no way of knowing the arguments of the output format including the final destination directory of the document. However it does have access to the `fig.path` knitr chunk option. Refer to [this](https://github.com/yihui/knitr/issues/1390) Github issue for a discussion around this. See the `bookdown` section below for a use case where this value needs to be explicitly set.
Another scenario where you may need to set this option is when your RMarkdown output format has `self_contained=TRUE` (Note: This is the `self_contained` argument of your HTML output format e.g. `rmarkdown::html_document` and not the `widgetframe_self_contained` chunk argument described above).
### Chunk Options and Output
To understand how each of the three knitr chunk options affect the wrapped widget's HTML document, see the code and the table below.
```r
```{r leaflet-01}
library(leaflet)
library(widgetframe)
l <- leaflet() %>% addTiles() %>% setView(0,0,1)
frameWidget(l, width='90%')
```
```{r dygraph-01}
library(dygraphs)
ts <- dygraph(nhtemp, main = "New Haven Temperatures")
frameWidget(ts, height = 350, width = '95%')
```
```
I've ommitted the `widgetframe_` prefix for each of the 3 options below to conserve space.
-------------------------------------------------------------------------------------------------------------------
`self_contained` `isolate_widgets` `widgets_dir` Output
-------------------- -------------------- -------------------- ----------------------------------------------------
`FALSE` <sup>†</sup> `TRUE` <sup>†</sup> Not Set <sup>†</sup> Inside `widgets` directory,
`widget_leaflet-01.html` and
`widget_dygraph-01.html` files and
`leaflet_libs` directory for `leaflet` and
`dygraph_libs` directory for `dygraph` dependencies.
`FALSE` <sup>†</sup> `FALSE` Not Set <sup>†</sup> Inside `widgets` directory,
`widget_leaflet-01.html` and
`widget_dygraph-01.html` files and
a single `libs` directory for
both `leaflet` and `dygraph` dependencies.
`TRUE` DOESN'T MATTER Not Set <sup>†</sup> Inside `widgets` directory,
two huge `widget_leaflet-01.html` and
`widget_dygraph-01.html` files with
respective dependencies inlined.
---------------------------------------------------------------------------------------------------------------------
†: Default Value.
By default the widget HTML + dependencies (JS/CSS files) are located inside `widgets` directory, which is created inside wherever `knitr::opts_chunk$get('fig.path')` points too. However if `widgetframe_widgets_dir` is set then the widget HTML + dependencies are placed inside a directory whose name is the value of this option, and the path is resolved relative to the current working directory (`getwd()`) while knitting.
## `widgetframe` and `bookdown`
For the [bookdown](https://bookdown.org/home/getting-started.html) output format, we need some additional steps to correctly use `widgetframe`s. This section describes those steps.
1. The default output directory of the `bookdown` book is `_book`, which can be configured via `_bookdown.yml` file.
2. For the `bookdown::gitbook` format we need to explicitly set the `widgetframe_widgets_dir` to some value (e.g. 'widgets'), so that the embedded widgets HTML code is saved in this directory instead of the default.
3. After `'bookdown::render_book("index.Rmd")` has been called, we need to move the widgets directory inside the final output directory.
You can easily use a Makefile for this. e.g.
Your `_bookdown.yml` file
```json
output_dir: "book"
```
and your `Makefile`
```makefile
book: index.Rmd
Rscript -e 'bookdown::render_book("index.Rmd")'
mv widgets book/.
```
and inside `index.Rmd` you should have something like
```r
```{r, include=FALSE}
knitr::opts_chunk$set(widgetframe_widgets_dir = 'widgets' )
```
```
|
/scratch/gouwar.j/cran-all/cranData/widgetframe/inst/doc/widgetframe_and_knitr.Rmd
|
---
title: "Using widgetframe"
author: "Bhaskar V. Karambelkar"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Using widgetframe}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
The `widgetframe` package eases embedding of `htmlwidgets` inside various HTML based R Markdown documents using iframes.
To make the iframes [responsive](https://en.wikipedia.org/wiki/Responsive_web_design) it uses NPR's [Pymjs](http://blog.apps.npr.org/pym.js/) library.
This package provides two primary functions, `frameableWidget`, and `frameWidget`. `frameableWidget` is used to add extra code to a `htmlwidgets` instance, which allows it to be rendered inside a responsive iframe. `frameWidget` returns a new `htmlwidgets` instance, which wraps and displays content of another `htmlwidgets` instance (e.g. `leaflet`, `DT` etc.) inside a responsive iframe.
### Current Status
For each of the document type below you can find fully working example code in the [Github Repo](https://github.com/bhaskarvk/widgetframe/tree/examples).
- Works With
* [Flex Dashboard](http://rmarkdown.rstudio.com/flexdashboard/): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/flexdashboard/dashboard.html).
* [RMarkdown](rmarkdown.rstudio.com) + [knitr](yihui.name/knitr/): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/rmarkdown/knitr_example.html).
* [RMarkdown Website](http://rmarkdown.rstudio.com/lesson-13.html): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/rmarkdown-website/site/index.html).
* [Xaringan Presentations](https://slides.yihui.name/xaringan/): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/xaringan/widgetframe.html#1).<br/>(May also work with other RMarkdown + knitr based presentations.)
* [Bookdown](https://bookdown.org/) gitbook: (Needs a Makefile for assembly). [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/bookdown/book/index.html).
* [blogdown](https://github.com/rstudio/blogdown/): [Demo](https://rawgit.com/bhaskarvk/widgetframe/examples/blogdown/public/index.html).
<br/>
- Does not (yet) work with
* Shiny: See [Github Issue](https://github.com/bhaskarvk/widgetframe/issues/11)
* Crosstalk: See [Github Issue](https://github.com/bhaskarvk/widgetframe/issues/3)
### Installation
Avaliable on [CRAN](https://cran.r-project.org/package=widgetframe) and can be installed using ...
```{r, eval=FALSE}
install.packages('widgetframe')
```
Or install the dev version from Github using `devtools` ...
```{r, eval=FALSE}
if(!require(devtools)) {
install.packages('devtools')
}
devtools::install_github('bhaskarvk/widgetframe')
```
### Usage
#### `frameableWidget` function.
The `frameableWidget` function should be used when you need a HTML which can be embedded in an external CMS like WordPress or Blogger, or a static HTML website.
```{r, eval=FALSE}
library(leaflet)
library(widgetframe)
l <- leaflet() %>% addTiles()
htmlwidgets::saveWidget(frameableWidget(l),'leaflet.html')
```
The resulting `leaflet.html` file contains the necessary Pym.js Child initialization code and will work inside a regular iFrame or better yet a Pym.js responsive iFrame. It is expected that the site which is going to embed this widget's content has the necessary Pymjs Parent initialization code as described [here](http://blog.apps.npr.org/pym.js/). The HTML dependencies of the widget (CSS/JS files) will be either inlined or kept external depending on the `seflcontained` argument to `saveWidget`.
#### `frameWidget` function
`frameWidget` function takes an existing `htmlwidgets` instance such as `leaflet` or `DT` etc., wraps it and returns a new `htmlwidgets` instance, which when rendered, displays the input wrapped `htmlwdigets` instance inside a responsive iFrame. This function can be used to knit htmlwidgets such that they are unaffected by the parent HTML file's CSS. This could be useful in [bookdown](https://bookdown.org/) or [R Markdown Websites](http://rmarkdown.rstudio.com/rmarkdown_websites.html) to embed widgets such that they are unaffected by the site's global CSS/JS.
```
```{r}
library(leaflet)
library(widgetframe)
l <- leaflet(height=300) %>% addTiles() %>% setView(0,0,1)
frameWidget(l)
```
```
```
```{r}
library(dygraphs)
ts <- dygraph(nhtemp, main = “New Haven Temperatures”,
height=250, width=‘95%’)
frameWidget(ts)
```
```
To know more about how `widgetframe` and `knitr`/`rmarkdown` work together, see the [`widgetframe` and `knitr`](widgetframe_and_knitr.html) vignette.
|
/scratch/gouwar.j/cran-all/cranData/widgetframe/vignettes/Using_widgetframe.Rmd
|
---
title: "widgetframe and knitr"
author: "Bhaskar V. Karambelkar"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{widgetframe and knitr}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## `knitr`
The [`knitr`](https://yihui.name/knitr/) package, along with the [`rmarkdown`](http://rmarkdown.rstudio.com/) package converts a R markdown (Rmd) document into a target document, which can be an HTML Document, a HTML Website, a Dashboard, or a PDF/Word Document etc.
`widgetframe` is designed to be used in Rmd documents which will eventually be knitted to an HTML or a derived format. There is little or no benefit in using `widgetframe::frameWidget()` when the output format is not HTML based such as PDF, Microsoft Word etc. In fact `widgetframe` will most definitely not work for such output formats.
## Regular `htmlwidgets` and `knitr`
By default when knitting `htmlwidgets` the `htmlwidgets:::knit_print.htmlwidgets()` function (an internal function exposed as an S3 method) is called. The output of this call is a `list` containing the HTML code + a list of HTML dependencies (JS/CSS) required to render the widget. How this is then inserted into the final document depends on the output format. For this discussion we are going to limit to HTML based output formats because as noted above `widgetframe` is designed to work only for HTML based output formats.
Let's start with the simplest of HTML output format `rmarkdown::html_document()`.
The `self_contained` (default = `TRUE`), and the `lib_dir` (default = name of document + `_files`)
arguments of this output format dictate how `htmlwidgets` instances appear in the final document. If `self_contained` is `TRUE` then the HTML dependencies (JS/CSS) are all inlined and the result is just one single HTML document. Naturally this document is quite large in size due to the dependencies being inlined. If `self_contained` is `FALSE` then the HTML dependencies are kept in a separate directory determined by the `lib_dir` argument. Other HTML based formats like `bookdown`, `flexdashboard` etc. too have similar arguments. This is not surprising as they tend to extend `rmarkdown::html_document`.
### Potential Issues
Unless you are working on small one-off Rmd document, it is never a good idea to have `self_contained` set to its default value `TRUE`. It results in large HTML documents which are slow to load in the browser. Secondly by inlining dependencies you lose the ability to share common dependencies across different HTMLs. Lastly you also limit the browser's ability to cache HTML dependencies across sessions.
Even if you were to externalize the dependencies by setting `sefl_contained=FALSE`, there are still two potential issues...
* Different `htmlwidgets` may depend on different versions of the same Javascript/CSS dependency. But when the final document is produced only a single version of the said dependency is used. This may cause certain widgets to not display, or work incorrectly.
* The styling rules (CSS) of the widget may be overridden by those of the output format. This will again result in the widget not displaying properly in the final document.
These problems typically don't occur when knitting one-off HTML documents using the `rmarkdown::html_document` format. But they do occur once you start outputting documents in the `bookdown`, `blogdown`, `rmarkdown` websites, `xaringan` and other HTML based output formats. And this is where `widgetframe` comes in.
## `widgetframe`
`widgetframe` is itself a `htmlwidgets` instance, but of a different kind. Instead of wrapping a Javascript based dataviz object, it wraps another `htmlwidgets` instance like `leaflet`, or `DT`, or `dygraphs` etc. It does so by embedding the target `htmlwidgets` instance in a HTML [iframe](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe). It also uses NPR's [pym.js](http://blog.apps.npr.org/pym.js/) Javascript library to make the iframes [responsive](https://en.wikipedia.org/wiki/Responsive_web_design). This allows you to easily embed `htmlwidgets` inside complex HTML documents and avoid the issues mentioned in the section above.
## `widgetframe` and `knitr`
To understand how the knitting of `widgetframe`s differ from regular `htmlwidgets`, let's examine the following code. It shows you how to use `widgetframe::fameWidget()` function in a RMarkdown document and the three knitr chunk options it supports.
```r
```{r, include=FALSE}
# widgetframe supports 3 custom knitr chunk options...
# For all practicle purposes this should always be FALSE
knitr::opts_chunk$set(widgetframe_self_contained = FALSE) # default = FALSE
# For all practicle purposes this should always be TRUE
knitr::opts_chunk$set(widgetframe_isolate_widgets = TRUE) # default = TRUE
# Only needed in bookdown format/s such as bookdown::gitbook. Otherwise don't set.
# knitr::opts_chunk$set(widgetframe_widgets_dir = 'widgets' )
```
```{r leaflet-01}
library(leaflet)
library(widgetframe)
l <- leaflet() %>% addTiles() %>% setView(0,0,1)
frameWidget(l, width='90%')
```
```
While using `wigdetframe` is as simple as `widgetframe::frameWidget(some_other_widget)`, how the widget is knitted depends on three custom knitr chunk options explained below. When `knitr` comes across a `widgetframe::frameWidget()` call in a R Markdown document, it calls `widgetframe:::knit_print.widgetframe()` function (internal function exposed as a S3 method) to render the widget. This function is a wrapper around the `htmlwidgets:::knit_print.htmlwidgets()` function of the taget `htmlwidgets` instance. It is important to know that both `knitr_print.widgetframe()` and `knitr_print.htmlwidgets()` functions have no way of knowing what the target output format is and what arguments were passed to the target output format. So in order to knit the target widget in a child HTML document, which is displayed inside an iframe of the parent HTML document, `widgetframe` needs to depend of the three chunk options shown in the code sample above. We now discuss these 3 options and what their values should be for different output formats.
### widgetfram_self_contained
This option is similar to the `self_contained` argument of the `rmarkdown::html_document()` output format. The reason we need a separate chucnk option is because ...
1. As explained above `knitr_print.widgetframe()` has no way of knowing what the output format is and what arguments were passed to it.
2. Unlike `self_contained` which defaults to `TRUE`, `widgetframe_self_contained` defaults to `FALSE`. That is to say that by default when using `widgetframe` the dependencies of the target `htmlwidgets` instance are kept in a separate directory.
There is very little reason to set this option to `TRUE`. If however you do set it to `TRUE` the HTML file for the wrapped widget will have its dependencies inlined, resulting in a single large HTML file. Note that this is not the same as your final output HTML. This is just the HTML for the widget which is displayed inside an iframe in the final HTML document.
Wheter the final HTML document has inlined dependencies depends on the `self_contaied` argument of your output format e.g. `rmarkdown::html_document()`.
### widgetframe_isolate_widgets
Defaults to `TRUE`, and when `TRUE`, isolates HTML dependencies (CSS/JS) of `htmlwidgets` of different types. This avoids compatibility issues when `htmlwidgets` of different types depend on the same dependency(ies) but on different versions. For example if you are using some `leaflet`, and some `DT` `htmlwdigets` in your document (doesn't matter how many), then the dependencies of `leaflet` widgets will be stored separately from dependencies of `DT` widgets and any other widget other than `leaflet`. So `leaflet` can depend on version 'X' of `jQuery` and `DT` can depend on version 'Y' and both will work correctly. Note that multiple widgets of the same type will share the same set of dependencies in order to avoid unnecessary duplication.
There is very little reason to set this option to `FALSE`.
### widgetframe_widgets_dir
This option, if provided, determines where the HTML code for the wrapped `htmlwidgets` instance is written. Before discussing more we should note that `knitr_print.htmlwidgets()` never actually creates any files/directories or touches the file-system in any way. It merely returns a R list which then used by the output format to embed the widget's HTML (and dependencies) in the final document. However, `knitr_print.widgetframe()` does create HTML file/s and dependencies directories for the wrapped widget. It needs to, so that the final document can embed the widget's HTML which is saved separately, inside an iframe. This may not be important to know from a user perspective but a must know, if you want to extend or contribute to `widgetframe`.
For almost all output formats except `bookdown`, this option should not be set and it will default to `file.path(knitr::opts_chunk$get('fig.path'),'widgets')`. That is a `widgets` directory inside the directory `knitr::opts_chunk$get('fig.path')`. This is done this way because as noted `knitr_print` has no way of knowing the arguments of the output format including the final destination directory of the document. However it does have access to the `fig.path` knitr chunk option. Refer to [this](https://github.com/yihui/knitr/issues/1390) Github issue for a discussion around this. See the `bookdown` section below for a use case where this value needs to be explicitly set.
Another scenario where you may need to set this option is when your RMarkdown output format has `self_contained=TRUE` (Note: This is the `self_contained` argument of your HTML output format e.g. `rmarkdown::html_document` and not the `widgetframe_self_contained` chunk argument described above).
### Chunk Options and Output
To understand how each of the three knitr chunk options affect the wrapped widget's HTML document, see the code and the table below.
```r
```{r leaflet-01}
library(leaflet)
library(widgetframe)
l <- leaflet() %>% addTiles() %>% setView(0,0,1)
frameWidget(l, width='90%')
```
```{r dygraph-01}
library(dygraphs)
ts <- dygraph(nhtemp, main = "New Haven Temperatures")
frameWidget(ts, height = 350, width = '95%')
```
```
I've ommitted the `widgetframe_` prefix for each of the 3 options below to conserve space.
-------------------------------------------------------------------------------------------------------------------
`self_contained` `isolate_widgets` `widgets_dir` Output
-------------------- -------------------- -------------------- ----------------------------------------------------
`FALSE` <sup>†</sup> `TRUE` <sup>†</sup> Not Set <sup>†</sup> Inside `widgets` directory,
`widget_leaflet-01.html` and
`widget_dygraph-01.html` files and
`leaflet_libs` directory for `leaflet` and
`dygraph_libs` directory for `dygraph` dependencies.
`FALSE` <sup>†</sup> `FALSE` Not Set <sup>†</sup> Inside `widgets` directory,
`widget_leaflet-01.html` and
`widget_dygraph-01.html` files and
a single `libs` directory for
both `leaflet` and `dygraph` dependencies.
`TRUE` DOESN'T MATTER Not Set <sup>†</sup> Inside `widgets` directory,
two huge `widget_leaflet-01.html` and
`widget_dygraph-01.html` files with
respective dependencies inlined.
---------------------------------------------------------------------------------------------------------------------
†: Default Value.
By default the widget HTML + dependencies (JS/CSS files) are located inside `widgets` directory, which is created inside wherever `knitr::opts_chunk$get('fig.path')` points too. However if `widgetframe_widgets_dir` is set then the widget HTML + dependencies are placed inside a directory whose name is the value of this option, and the path is resolved relative to the current working directory (`getwd()`) while knitting.
## `widgetframe` and `bookdown`
For the [bookdown](https://bookdown.org/home/getting-started.html) output format, we need some additional steps to correctly use `widgetframe`s. This section describes those steps.
1. The default output directory of the `bookdown` book is `_book`, which can be configured via `_bookdown.yml` file.
2. For the `bookdown::gitbook` format we need to explicitly set the `widgetframe_widgets_dir` to some value (e.g. 'widgets'), so that the embedded widgets HTML code is saved in this directory instead of the default.
3. After `'bookdown::render_book("index.Rmd")` has been called, we need to move the widgets directory inside the final output directory.
You can easily use a Makefile for this. e.g.
Your `_bookdown.yml` file
```json
output_dir: "book"
```
and your `Makefile`
```makefile
book: index.Rmd
Rscript -e 'bookdown::render_book("index.Rmd")'
mv widgets book/.
```
and inside `index.Rmd` you should have something like
```r
```{r, include=FALSE}
knitr::opts_chunk$set(widgetframe_widgets_dir = 'widgets' )
```
```
|
/scratch/gouwar.j/cran-all/cranData/widgetframe/vignettes/widgetframe_and_knitr.Rmd
|
#' Find the Pearson correlation of a sparse matrix efficiently
#'
#' Find the Pearson correlation of a sparse matrix.
#' For large sparse matrix this is more efficient in time and memory than
#' `cor(as.matrix(x))`. Note that it does not currently work on
#' simple_triplet_matrix objects.
#'
#' @param x A matrix, potentially a sparse matrix such as a "dgTMatrix" object
#'
#' @source This code comes from mike on this Stack Overflow answer:
#' <https://stackoverflow.com/a/9626089/712603>.
cor_sparse <- function(x) {
n <- nrow(x)
covmat <- (as.matrix(crossprod(x)) - n * tcrossprod(colMeans(x))) / (n - 1)
cormat <- covmat / tcrossprod(sqrt(diag(covmat)))
cormat
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/cor_sparse.R
|
globalVariables(c("item1", "item2", "value", "..data", "data",
"item", "cluster"))
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/globals.R
|
#' Correlations of pairs of items
#'
#' Find correlations of pairs of items in a column, based on a "feature" column
#' that links them together. This is an example of the spread-operate-retidy pattern.
#'
#' @param tbl Table
#' @param item Item to compare; will end up in `item1` and
#' `item2` columns
#' @param feature Column describing the feature that links one item to others
#' @param value Value column. If not given, defaults to all values being 1 (thus
#' a binary correlation)
#' @param method Correlation method
#' @param use Character string specifying the behavior of correlations
#' with missing values; passed on to `cor`
#' @param ... Extra arguments passed on to `squarely`,
#' such as `diag` and `upper`
#'
#' @examples
#'
#' library(dplyr)
#' library(gapminder)
#'
#' gapminder %>%
#' pairwise_cor(country, year, lifeExp)
#'
#' gapminder %>%
#' pairwise_cor(country, year, lifeExp, sort = TRUE)
#'
#' # United Nations voting data
#' if (require("unvotes", quietly = TRUE)) {
#' country_cors <- un_votes %>%
#' mutate(vote = as.numeric(vote)) %>%
#' pairwise_cor(country, rcid, vote, sort = TRUE)
#' }
#'
#' @export
pairwise_cor <- function(tbl, item, feature, value,
method = c("pearson", "kendall", "spearman"),
use = "everything", ...) {
if (missing(value)) {
tbl$..value <- 1
val <- "..value"
} else {
val <- col_name(substitute(value))
}
pairwise_cor_(tbl,
col_name(substitute(item)),
col_name(substitute(feature)),
val,
method = method, use = use, ...)
}
#' @rdname pairwise_cor
#' @export
pairwise_cor_ <- function(tbl, item, feature, value,
method = c("pearson", "kendall", "spearman"),
use = "everything",
...) {
method <- match.arg(method)
sparse <- (method == "pearson" & use == "everything")
f <- if (sparse) {
function(x) cor_sparse(t(x))
} else {
function(x) stats::cor(t(x), method = method, use = use)
}
cor_func <- squarely_(f, sparse = sparse, ...)
tbl %>%
ungroup() %>%
cor_func(item, feature, value) %>%
rename(correlation = value)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/pairwise_cor.R
|
#' Count pairs of items within a group
#'
#' Count the number of times each pair of items appear together within a group
#' defined by "feature." For example, this could count the number of times
#' two words appear within documents).
#'
#' @param tbl Table
#' @param item Item to count pairs of; will end up in `item1` and
#' `item2` columns
#' @param feature Column within which to count pairs
#' `item2` columns
#' @param wt Optionally a weight column, which should have a consistent weight
#' for each feature
#' @param ... Extra arguments passed on to `squarely`,
#' such as `diag`, `upper`, and `sort`
#'
#' @seealso [squarely()]
#'
#' @examples
#'
#' library(dplyr)
#' dat <- tibble(group = rep(1:5, each = 2),
#' letter = c("a", "b",
#' "a", "c",
#' "a", "c",
#' "b", "e",
#' "b", "f"))
#'
#' # count the number of times two letters appear together
#' pairwise_count(dat, letter, group)
#' pairwise_count(dat, letter, group, sort = TRUE)
#' pairwise_count(dat, letter, group, sort = TRUE, diag = TRUE)
#'
#' @export
pairwise_count <- function(tbl, item, feature, wt = NULL, ...) {
pairwise_count_(tbl,
col_name(substitute(item)),
col_name(substitute(feature)),
wt = col_name(substitute(wt)),
...)
}
#' @rdname pairwise_count
#' @export
pairwise_count_ <- function(tbl, item, feature, wt = NULL, ...) {
if (is.null(wt)) {
func <- squarely_(function(m) m %*% t(m), sparse = TRUE, ...)
wt <- "..value"
} else {
func <- squarely_(function(m) m %*% t(m > 0), sparse = TRUE, ...)
}
tbl %>%
distinct(.data[[item]], .data[[feature]], .keep_all = TRUE) %>%
mutate(..value = 1) %>%
func(item, feature, wt) %>%
rename(n = value)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/pairwise_count.R
|
#' Delta measure of pairs of documents
#'
#' Compute the delta distances (from its two variants) of all pairs of documents in a tidy table.
#'
#' @param tbl Table
#' @param item Item to compare; will end up in `item1` and
#' `item2` columns
#' @param feature Column describing the feature that links one item to others
#' @param value Value
#' @param method Distance measure to be used; see [dist()]
#' @param ... Extra arguments passed on to [squarely()],
#' such as `diag` and `upper`
#'
#' @seealso [squarely()]
#'
#' @examples
#'
#' library(janeaustenr)
#' library(dplyr)
#' library(tidytext)
#'
#' # closest documents in terms of 1000 most frequent words
#' closest <- austen_books() %>%
#' unnest_tokens(word, text) %>%
#' count(book, word) %>%
#' top_n(1000, n) %>%
#' pairwise_delta(book, word, n, method = "burrows") %>%
#' arrange(delta)
#'
#' closest
#'
#' closest %>%
#' filter(item1 == "Pride & Prejudice")
#'
#' # to remove duplicates, use upper = FALSE
#' closest <- austen_books() %>%
#' unnest_tokens(word, text) %>%
#' count(book, word) %>%
#' top_n(1000, n) %>%
#' pairwise_delta(book, word, n, method = "burrows", upper = FALSE) %>%
#' arrange(delta)
#'
#' # Can also use Argamon's Linear Delta
#' closest <- austen_books() %>%
#' unnest_tokens(word, text) %>%
#' count(book, word) %>%
#' top_n(1000, n) %>%
#' pairwise_delta(book, word, n, method = "argamon", upper = FALSE) %>%
#' arrange(delta)
#'
#' @export
pairwise_delta <- function(tbl, item, feature, value,
method = "burrows", ...) {
pairwise_delta_(tbl,
col_name(substitute(item)),
col_name(substitute(feature)),
col_name(substitute(value)),
method = method, ...)
}
#' @rdname pairwise_delta
#' @export
pairwise_delta_ <- function(tbl, item, feature, value, method = "burrows", ...) {
delta_func <- function(m) {
if(method == "burrows") {
dist_method = "manhattan"
}
else if(method == "argamon") {
dist_method = "euclidean"
}
else {
stop("Wrong method! Only method = burrows or method = argamon have been implmented!")
}
return(as.matrix(stats::dist(scale(m), method = dist_method)/length(m[1,])))
}
d_func <- squarely_(delta_func, ...)
tbl %>%
d_func(item, feature, value) %>%
rename(delta = value)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/pairwise_delta.R
|
#' Distances of pairs of items
#'
#' Compute distances of all pairs of items in a tidy table.
#'
#' @param tbl Table
#' @param item Item to compare; will end up in `item1` and
#' `item2` columns
#' @param feature Column describing the feature that links one item to others
#' @param value Value
#' @param method Distance measure to be used; see [dist()]
#' @param ... Extra arguments passed on to [squarely()],
#' such as `diag` and `upper`
#'
#' @seealso [squarely()]
#'
#' @examples
#'
#' library(gapminder)
#' library(dplyr)
#'
#' # closest countries in terms of life expectancy over time
#' closest <- gapminder %>%
#' pairwise_dist(country, year, lifeExp) %>%
#' arrange(distance)
#'
#' closest
#'
#' closest %>%
#' filter(item1 == "United States")
#'
#' # to remove duplicates, use upper = FALSE
#' gapminder %>%
#' pairwise_dist(country, year, lifeExp, upper = FALSE) %>%
#' arrange(distance)
#'
#' # Can also use Manhattan distance
#' gapminder %>%
#' pairwise_dist(country, year, lifeExp, method = "manhattan", upper = FALSE) %>%
#' arrange(distance)
#'
#' @export
pairwise_dist <- function(tbl, item, feature, value,
method = "euclidean", ...) {
pairwise_dist_(tbl,
col_name(substitute(item)),
col_name(substitute(feature)),
col_name(substitute(value)),
method = method, ...)
}
#' @rdname pairwise_dist
#' @export
pairwise_dist_ <- function(tbl, item, feature, value, method = "euclidean", ...) {
d_func <- squarely_(function(m) as.matrix(stats::dist(m, method = method)), ...)
tbl %>%
d_func(item, feature, value) %>%
rename(distance = value)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/pairwise_dist.R
|
#' Pointwise mutual information of pairs of items
#'
#' Find pointwise mutual information of pairs of items in a column, based on
#' a "feature" column that links them together.
#' This is an example of the spread-operate-retidy pattern.
#'
#' @param tbl Table
#' @param item Item to compare; will end up in `item1` and
#' `item2` columns
#' @param feature Column describing the feature that links one item to others
#' @param sort Whether to sort in descending order of the pointwise mutual
#' information
#' @param ... Extra arguments passed on to `squarely`,
#' such as `diag` and `upper`
#'
#' @name pairwise_pmi
#'
#' @return A tbl_df with three columns, `item1`, `item2`, and
#' `pmi`.
#'
#' @examples
#'
#' library(dplyr)
#'
#' dat <- tibble(group = rep(1:5, each = 2),
#' letter = c("a", "b",
#' "a", "c",
#' "a", "c",
#' "b", "e",
#' "b", "f"))
#'
#' # how informative is each letter about each other letter
#' pairwise_pmi(dat, letter, group)
#' pairwise_pmi(dat, letter, group, sort = TRUE)
#'
#' @export
pairwise_pmi <- function(tbl, item, feature, sort = FALSE, ...) {
pairwise_pmi_(tbl,
col_name(substitute(item)),
col_name(substitute(feature)),
sort = sort, ...)
}
#' @rdname pairwise_pmi
#' @export
pairwise_pmi_ <- function(tbl, item, feature, sort = FALSE, ...) {
f <- function(m) {
row_sums <- rowSums(m) / sum(m)
ret <- m %*% t(m)
ret <- ret / sum(ret)
ret <- ret / row_sums
ret <- t(t(ret) / (row_sums))
ret
}
pmi_func <- squarely_(f, sparse = TRUE, sort = sort, ...)
tbl %>%
ungroup() %>%
mutate(..value = 1) %>%
pmi_func(item, feature, "..value") %>%
mutate(value = log(value)) %>%
rename(pmi = value)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/pairwise_pmi.R
|
#' Cosine similarity of pairs of items
#'
#' Compute cosine similarity of all pairs of items in a tidy table.
#'
#' @param tbl Table
#' @param item Item to compare; will end up in `item1` and
#' `item2` columns
#' @param feature Column describing the feature that links one item to others
#' @param value Value
#' @param ... Extra arguments passed on to [squarely()],
#' such as `diag` and `upper`
#'
#' @seealso [squarely()]
#'
#' @examples
#'
#' library(janeaustenr)
#' library(dplyr)
#' library(tidytext)
#'
#' # Comparing Jane Austen novels
#' austen_words <- austen_books() %>%
#' unnest_tokens(word, text) %>%
#' anti_join(stop_words, by = "word") %>%
#' count(book, word) %>%
#' ungroup()
#'
#' # closest books to each other
#' closest <- austen_words %>%
#' pairwise_similarity(book, word, n) %>%
#' arrange(desc(similarity))
#'
#' closest
#'
#' closest %>%
#' filter(item1 == "Emma")
#'
#' @export
pairwise_similarity <- function(tbl, item, feature, value, ...) {
pairwise_similarity_(tbl,
col_name(substitute(item)),
col_name(substitute(feature)),
col_name(substitute(value)), ...)
}
#' @rdname pairwise_similarity
#' @export
pairwise_similarity_ <- function(tbl, item, feature, value, ...) {
m <- matrix(1:9, ncol = 3)
d_func <- squarely_(function(m) {
normed <- m / sqrt(rowSums(m ^ 2))
normed %*% t(normed)
}, sparse = TRUE, ...)
tbl %>%
d_func(item, feature, value) %>%
rename(similarity = value)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/pairwise_similarity.R
|
#' A special case of the widely adverb for creating tidy
#' square matrices
#'
#' A special case of [widely()]. Used to pre-prepare and
#' post-tidy functions that take an m x n (m items, n features)
#' matrix and return an m x m (item x item) matrix, such as a
#' distance or correlation matrix.
#'
#' @param .f Function to wrap
#' @param diag Whether to include diagonal (i = j) in output
#' @param upper Whether to include upper triangle, which may be
#' duplicated
#' @param ... Extra arguments passed on to `widely`
#'
#' @return Returns a function that takes at least four arguments:
#' \item{tbl}{A table}
#' \item{item}{Name of column to use as rows in wide matrix}
#' \item{feature}{Name of column to use as columns in wide matrix}
#' \item{feature}{Name of column to use as values in wide matrix}
#' \item{...}{Arguments passed on to inner function}
#'
#' @seealso [widely()], [pairwise_count()],
#' [pairwise_cor()], [pairwise_dist()]
#'
#' @examples
#'
#' library(dplyr)
#' library(gapminder)
#'
#' closest_continent <- gapminder %>%
#' group_by(continent) %>%
#' squarely(dist)(country, year, lifeExp)
#'
#' @export
squarely <- function(.f, diag = FALSE, upper = TRUE, ...) {
inner_func <- squarely_(.f, diag = diag, upper = upper, ...)
function(tbl, item, feature, value, ...) {
inner_func(tbl,
col_name(substitute(item)),
col_name(substitute(feature)),
col_name(substitute(value)),
...)
}
}
#' @rdname squarely
#' @export
squarely_ <- function(.f, diag = FALSE,
upper = TRUE,
...) {
extra_args <- list(...)
f <- function(tbl, item, feature, value, ...) {
if (inherits(tbl, "grouped_df")) {
# perform within each group, then restore groups
ret <- tbl %>%
tidyr::nest() %>%
mutate(data = purrr::map(data, f, item, feature, value)) %>%
filter(purrr::map_lgl(data, ~ nrow(.) > 0)) %>%
tidyr::unnest(data) %>%
dplyr::group_by_at(dplyr::group_vars(tbl))
return(ret)
}
item_vals <- tbl[[item]]
item_u <- unique(item_vals)
tbl[[item]] <- match(item_vals, item_u)
new_f <- do.call(widely_, c(list(.f), extra_args))
ret <- new_f(tbl, item, feature, value, ...)
ret$item1 <- as.integer(ret$item1)
ret$item2 <- as.integer(ret$item2)
if (!upper) {
ret <- dplyr::filter(ret, item1 <= item2)
}
if (!diag) {
ret <- dplyr::filter(ret, item1 != item2)
}
ret$item1 <- item_u[ret$item1]
ret$item2 <- item_u[ret$item2]
ret
}
f
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/squarely.R
|
#' Comes from tidyr
#' @noRd
col_name <- function(x, default = stop("Please supply column name", call. = FALSE))
{
if (is.character(x))
return(x)
if (identical(x, quote(expr = )))
return(default)
if (is.name(x))
return(as.character(x))
if (is.null(x))
return(x)
stop("Invalid column specification", call. = FALSE)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/utils.R
|
#' Adverb for functions that operate on matrices in "wide"
#' format
#'
#' Modify a function in order to pre-cast the input into a wide
#' matrix format, perform the function, and then
#' re-tidy (e.g. melt) the output into a tidy table.
#'
#' @param .f Function being wrapped
#' @param sort Whether to sort in descending order of `value`
#' @param maximum_size To prevent crashing, a maximum size of a
#' non-sparse matrix to be created. Set to NULL to allow any size
#' matrix.
#' @param sparse Whether to cast to a sparse matrix
#'
#' @return Returns a function that takes at least four arguments:
#' \item{tbl}{A table}
#' \item{row}{Name of column to use as rows in wide matrix}
#' \item{column}{Name of column to use as columns in wide matrix}
#' \item{value}{Name of column to use as values in wide matrix}
#' \item{...}{Arguments passed on to inner function}
#'
#' `widely` creates a function that takes those columns as
#' bare names, `widely_` a function that takes them as strings.
#'
#' @import dplyr
#' @import Matrix
#' @importFrom broom tidy
#'
#' @examples
#'
#' library(dplyr)
#' library(gapminder)
#'
#' gapminder
#'
#' gapminder %>%
#' widely(dist)(country, year, lifeExp)
#'
#' # can perform within groups
#' closest_continent <- gapminder %>%
#' group_by(continent) %>%
#' widely(dist)(country, year, lifeExp)
#' closest_continent
#'
#' # for example, find the closest pair in each
#' closest_continent %>%
#' top_n(1, -value)
#'
#' @export
widely <- function(.f,
sort = FALSE,
sparse = FALSE,
maximum_size = 1e7) {
function(tbl, row, column, value, ...) {
inner_func <- widely_(.f,
sort = sort,
sparse = sparse,
maximum_size = maximum_size)
inner_func(tbl,
col_name(substitute(row)),
col_name(substitute(column)),
col_name(substitute(value)),
...)
}
}
#' @rdname widely
#' @export
widely_ <- function(.f,
sort = FALSE,
sparse = FALSE,
maximum_size = 1e7) {
f <- function(tbl, row, column, value, ...) {
if (inherits(tbl, "grouped_df")) {
# perform within each group
# (group_by_at isn't necessary since 1.0.0, but is in earlier versions)
ret <- tbl %>%
tidyr::nest() %>%
mutate(data = purrr::map(data, f, row, column, value)) %>%
tidyr::unnest(data) %>%
dplyr::group_by_at(dplyr::group_vars(tbl))
return(ret)
}
if (!sparse) {
if (!is.null(maximum_size)) {
matrix_size <- (length(unique(tbl[[row]])) *
length(unique(tbl[[column]])))
if (matrix_size > maximum_size) {
rlang::abort(
paste0("Size of acast matrix, ", matrix_size,
" will be too large. Set maximum_size = NULL to avoid ",
"this error (make sure your memory is sufficient), ",
"or consider using sparse = TRUE.")
)
}
}
form <- stats::as.formula(paste(row, column, sep = " ~ "))
input <- reshape2::acast(tbl, form, value.var = value, fill = 0)
} else {
input <- tidytext::cast_sparse(tbl, !!row, !!column, !!value)
}
output <- purrr::as_mapper(.f)(input, ...)
ret <- output %>%
custom_melt() %>%
as_tibble()
if (sort) {
ret <- arrange(ret, desc(value))
}
ret
}
f
}
#' Tidy a function output based on some guesses
#' @noRd
custom_melt <- function(m) {
if (inherits(m, "data.frame")) {
rlang::abort("Output is a data frame: don't know how to fix")
} else if (inherits(m, "matrix")) {
ret <- reshape2::melt(m, varnames = c("item1", "item2"), as.is = TRUE)
return(ret)
} else if (inherits(m, "Matrix")) {
ret <- sparse_matrix_to_df(m)
} else {
ret <- tidy(m)
}
colnames(ret) <- c("item1", "item2", "value")
ret
}
sparse_matrix_to_df <- function(x) {
s <- Matrix::summary(x)
row <- s$i
if (!is.null(rownames(x))) {
row <- rownames(x)[row]
}
col <- s$j
if (!is.null(colnames(x))) {
col <- colnames(x)[col]
}
ret <- data.frame(
row = row, column = col, value = s$x,
stringsAsFactors = FALSE
)
ret
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/widely.R
|
#' Cluster pairs of items into groups using hierarchical clustering
#'
#' Reshape a table that represents pairwise distances into hierarchical clusters,
#' returning a table with `item` and `cluster` columns.
#'
#' @param tbl Table
#' @param item1 First item
#' @param item2 Second item
#' @param distance Distance column
#' @param k The desired number of groups
#' @param h Height at which to cut the hierarchically clustered tree
#'
#' @examples
#'
#' library(gapminder)
#' library(dplyr)
#'
#' # Construct Euclidean distances between countries based on life
#' # expectancy over time
#' country_distances <- gapminder %>%
#' pairwise_dist(country, year, lifeExp)
#'
#' country_distances
#'
#' # Turn this into 5 hierarchical clusters
#' clusters <- country_distances %>%
#' widely_hclust(item1, item2, distance, k = 8)
#'
#' # Examine a few such clusters
#' clusters %>% filter(cluster == 1)
#' clusters %>% filter(cluster == 2)
#'
#' @seealso [cutree]
#'
#' @export
widely_hclust <- function(tbl, item1, item2, distance, k = NULL, h = NULL) {
col1_str <- as.character(substitute(item1))
col2_str <- as.character(substitute(item2))
dist_str <- as.character(substitute(distance))
unique_items <- unique(c(as.character(tbl[[col1_str]]), as.character(tbl[[col2_str]])))
form <- stats::as.formula(paste(col1_str, "~", col2_str))
max_distance <- max(tbl[[dist_str]])
tibble(item1 = match(tbl[[col1_str]], unique_items),
item2 = match(tbl[[col2_str]], unique_items),
distance = tbl[[dist_str]]) %>%
reshape2::acast(item1 ~ item2, value.var = "distance", fill = max_distance) %>%
stats::as.dist() %>%
stats::hclust() %>%
stats::cutree(k = k, h = h) %>%
tibble::enframe("item", "cluster") %>%
dplyr::mutate(item = unique_items[as.integer(item)],
cluster = factor(cluster)) %>%
dplyr::arrange(cluster)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/widely_hclust.R
|
#' Cluster items based on k-means across features
#'
#' Given a tidy table of features describing each item, perform k-means
#' clustering using [kmeans()] and retidy the data into
#' one-row-per-cluster.
#'
#' @param tbl Table
#' @param item Item to cluster (as a bare column name)
#' @param feature Feature column (dimension in clustering)
#' @param value Value column
#' @param k Number of clusters
#' @param fill What to fill in for missing values
#' @param ... Other arguments passed on to [kmeans()]
#'
#' @seealso [widely_hclust()]
#'
#' @importFrom rlang :=
#'
#' @examples
#'
#' library(gapminder)
#' library(dplyr)
#'
#' clusters <- gapminder %>%
#' widely_kmeans(country, year, lifeExp, k = 5)
#'
#' clusters
#'
#' clusters %>%
#' count(cluster)
#'
#' # Examine a few clusters
#' clusters %>% filter(cluster == 1)
#' clusters %>% filter(cluster == 2)
#'
#' @export
widely_kmeans <- function(tbl, item, feature, value, k, fill = 0, ...) {
item_str <- as.character(substitute(item))
feature_str <- as.character(substitute(feature))
value_str <- as.character(substitute(value))
form <- stats::as.formula(paste(item_str, "~", feature_str))
m <- tbl %>%
reshape2::acast(form, value.var = value_str, fill = fill)
clustered <- stats::kmeans(m, k, ...)
# Add the clusters to the original table
i <- match(rownames(m), as.character(tbl[[item_str]]))
tibble::tibble(!!sym(item_str) := tbl[[item_str]][i],
cluster = factor(clustered$cluster)) %>%
dplyr::arrange(cluster)
}
|
/scratch/gouwar.j/cran-all/cranData/widyr/R/widely_kmeans.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.