├── .Rbuildignore ├── .gitignore ├── .travis.yml ├── DESCRIPTION ├── NAMESPACE ├── R ├── LRtestvar.R ├── acipair-data.R ├── alliance-data.R ├── apim.R ├── confintLME.R ├── counts_labels.R ├── crsp.R ├── dyadic_trade-data.R ├── getevd.R ├── graphMod.R ├── lincomb.R ├── mmc.R ├── smallsummary.R ├── sobel.R ├── testvar.R ├── var_labels.R └── variable_view.R ├── README.Rmd ├── README.md ├── data ├── acipair.RData ├── alliance.rda └── dyadic_trade.rda ├── dyadr.Rproj ├── man ├── LRtestvar.Rd ├── acipair.Rd ├── alliance.Rd ├── apim.Rd ├── confintLME.Rd ├── counts_labels.Rd ├── crsp.Rd ├── dyadic_trade.Rd ├── getevd.Rd ├── graphMod.Rd ├── lincomb.Rd ├── mmc.Rd ├── smallsummary.Rd ├── sobel.Rd ├── testvar.Rd ├── var_labels.Rd └── variable_view.Rd ├── tests ├── testthat.R └── testthat │ └── test_dyadr.R └── vignettes ├── .gitignore └── dyadr_vignette.Rmd /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^\.travis\.yml$ 4 | ^README\.Rmd$ 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | inst/doc 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # R for travis: see documentation at https://docs.travis-ci.com/user/languages/r 2 | 3 | language: r 4 | cache: packages 5 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: dyadr 2 | Title: dyadr: Dyadic Data Analysis 3 | Version: 0.0.0.9000 4 | Authors@R: c( 5 | person("Randi", "Garcia", email = "rgarcia@smith.edu", role=(c("aut", "cre"))), 6 | person("David", "Kenny", email = "david.kenny@uconn.edu", role = "aut"), 7 | person("Rutendo", "Madziwo", email = "rmadziwo@smith.edu", role = "ctb"), 8 | person("Emma", "Livingston", email = "livingston.emma73@gmail.com", role = "ctb"), 9 | person("Sifan", "Liu", email = "cliu13@smith.edu", role = "ctb"), 10 | person("Alina", "Barylsky", email = "abarylsky@gmail.com", role = "ctb"), 11 | person("Jane", "Bang", email = "carolbjy@gmail.com", role = "ctb")) 12 | Description: This package provides helper functions for dyadic data analysis. 13 | Depends: 14 | R (>= 3.2.3) 15 | License: CC0 16 | Encoding: UTF-8 17 | LazyData: true 18 | RoxygenNote: 7.1.1 19 | Imports: 20 | tibble, 21 | dplyr, 22 | sjlabelled, 23 | nlme, 24 | MASS, 25 | stringr, 26 | stringi, 27 | stats, 28 | ggplot2, 29 | lazyeval, 30 | qtl 31 | Suggests: 32 | testthat, 33 | knitr, 34 | rmarkdown 35 | VignetteBuilder: knitr 36 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(LRtestvar) 4 | export(apim) 5 | export(confintLME) 6 | export(counts_labels) 7 | export(crsp) 8 | export(getevd) 9 | export(graphMod) 10 | export(lincomb) 11 | export(mmc) 12 | export(smallsummary) 13 | export(sobel) 14 | export(testvar) 15 | export(var_labels) 16 | export(variable_view) 17 | import(dplyr) 18 | import(ggplot2) 19 | import(lazyeval) 20 | import(qtl) 21 | import(stringr) 22 | importFrom(MASS,mvrnorm) 23 | importFrom(stats,as.formula) 24 | importFrom(stats,confint) 25 | importFrom(stats,formula) 26 | importFrom(stats,logLik) 27 | importFrom(stats,pchisq) 28 | importFrom(stats,pnorm) 29 | importFrom(stats,quantile) 30 | importFrom(stringi,stri_length) 31 | -------------------------------------------------------------------------------- /R/LRtestvar.R: -------------------------------------------------------------------------------- 1 | #' @name LRtestvar 2 | #' @title Test the variance of a random effect 3 | #' 4 | #' @param outp the lme model object. 5 | #' @param p string variable that you want to test the random variance component for. 6 | #' @param ctrl an lmeControl object. Defaults to msMaxIter=10000, MaxIter=100000, msMaxEval=10000, returnObject=TRUE, niterEM=10000, nlmStepMax=1000. 7 | #' @import stringr 8 | #' @importFrom stats as.formula formula logLik pchisq 9 | #' @importFrom stringi stri_length 10 | #' @details LRtestvar(dyadGC_full, "MTime") 11 | #' @export 12 | #' 13 | LRtestvar <- function(outp, p, ctrl = defaultctrl){ 14 | defaultctrl <- lmeControl(msMaxIter=10000, 15 | MaxIter=100000, 16 | msMaxEval=10000, 17 | returnObject=TRUE, 18 | niterEM=10000, 19 | nlmStepMax=1000) 20 | 21 | args <- as.character(outp$call) 22 | 23 | #relying on the -1 in the random effects 24 | new <- substr(str_remove(args[4], "~"), 25 | 1, 26 | str_locate(str_remove(args[4], "~"),"-")-1) 27 | 28 | ran_list = str_remove_all(unlist(str_split(new, "\\+")), " ") 29 | ran_end = substr(args[4], str_locate(args[4], "-"), stri_length(args[4])) 30 | 31 | #stripped formulas and data from model call 32 | out = str_remove_all(substr(args[2], 1, str_locate(args[2], "~")-1), " ") 33 | mfm = as.formula(args[2]) 34 | dat = get(args[3]) 35 | mcor = formula(substr(args[5], str_locate(args[5], "~"), stri_length(args[5])-1)) 36 | mwei = formula(substr(args[6], str_locate(args[6], "~"), stri_length(args[6])-1)) 37 | nact = args[7] 38 | 39 | #different random effects 40 | mran_full <- formula(args[4]) 41 | 42 | mran_omit <- formula(str_c("~", str_c(ran_list[!str_detect(ran_list, str_c("^",p,"$"))], collapse = "+"), 43 | ran_end, collapse = "")) 44 | 45 | fm1 <- formula(str_remove_all(str_c("~", 46 | str_c(ran_list[!str_detect(ran_list, str_c("^",p,"$"))], collapse = "+"), 47 | "-1", collapse = ""), " ")) 48 | fm2 <- formula(str_remove_all(str_c("~", 49 | p, 50 | "-1", collapse = ""), " ")) 51 | 52 | dyd <- substr(args[4], str_locate(args[4], "\\|")+1, stri_length(args[4])) 53 | dyd <- str_remove_all(dyd, " ") 54 | obs <- substr(args[5], str_locate(args[5], "/")+1, stri_length(args[5])-1) 55 | 56 | dat$dyd=dat[,dyd] 57 | dat$obs=dat[,obs] 58 | 59 | mod_omit <- lme(mfm, data = dat, 60 | random = mran_omit, 61 | correlation = corCompSymm(form = mcor), 62 | weights = varIdent(form = mwei), 63 | na.action = nact, 64 | control = ctrl) 65 | 66 | mod_sep <- lme(mfm, data = dat, 67 | random = list(dyd = 68 | pdBlocked(list(fm1, fm2))), 69 | correlation = corCompSymm(form = ~1|dyd/obs), 70 | weights = varIdent(form = mwei), 71 | na.action = nact, 72 | control = ctrl) 73 | 74 | pvalCorrected <- function(chisq, df){ 75 | (pchisq(chisq, df, lower.tail=FALSE) + pchisq(chisq, df - 1, lower.tail=FALSE))/2 76 | } 77 | 78 | fff=-2*logLik(mod_omit)[1]+2*logLik(mod_sep)[1] 79 | 80 | return(data.frame(Outcome = out, 81 | VarComponent = p, 82 | Chi_Squared = -2*logLik(mod_omit)[1]+2*logLik(mod_sep)[1], 83 | df = 1, 84 | p_value = pvalCorrected(as.numeric(fff), 1))) 85 | } 86 | 87 | globalVariables(c("lmeControl","pdBlocked","varIdent","stri_length")) 88 | -------------------------------------------------------------------------------- /R/acipair-data.R: -------------------------------------------------------------------------------- 1 | #' Acitelli Data 2 | #' 3 | #' Data from 148 heterosexual married couples in Detroit 4 | #' 5 | #' @docType data 6 | #' @import qtl 7 | #' @usage data(acipair) 8 | #' 9 | #' @format An object of class \code{"cross"}; see \code{\link[qtl]{read.cross}}. 10 | #' 11 | #' @keywords datasets 12 | #' 13 | #' @examples 14 | #' data(acipair) 15 | #' \donttest{iplotCurves(phe, times)} 16 | "acipair" 17 | -------------------------------------------------------------------------------- /R/alliance-data.R: -------------------------------------------------------------------------------- 1 | #' Alliance Data 2 | #' 3 | #' Data from Gibler (2009) paper about International military alliances contains the alliance dataset distributed by directed-dyad, with one observation for each directed-dyad alliance initiation, with data on 414 countries. 4 | #' 5 | #'@docType data 6 | #' 7 | #'@usage data(alliance) 8 | #' 9 | #'@keywords datasets 10 | #' 11 | #'@format A data frame with 3252 rows and 18 variables: 12 | #'\describe{ 13 | #' \item{version4id}{the unique serial identification number for each alliance} 14 | #' \item{ccode1}{the Correlates of War System Membership number of the state initiating alliance terms toward ccode2} 15 | #' \item{state_name1}{the Correlates of War System Membership name of ccode1} 16 | #' \item{ccode2}{the Correlates of War System Membership number of the state receiving alliance terms from ccode1} 17 | #' \item{state_name2}{the Correlates of War System Membership name of ccode2} 18 | #' \item{dyad_st_day}{the day of entry into the Correlates of War system for the allied dyad} 19 | #' \item{dyad_st_month}{the month of entry into the Correlates of War system for the allied dyad} 20 | #' \item{dyad_st_year}{the year of entry into the Correlates of War system for the allied dyad} 21 | #' \item{dyad_end_day}{the day of alliance entry for the directed-dyad observation; missing data denotes alliance is still in effect as of 12/31/2012} 22 | #' \item{dyad_end_month}{the month of alliance entry for the directed-dyad observation; missing data denotes alliance is still in effect as of 12/31/2012} 23 | #' \item{dyad_end_year}{the year of alliance entry for the directed-dyad observation; missing data denotes alliance is still in effect as of 12/31/2012} 24 | #' \item{left_censor}{coded as (1) if the directed-dyad entered the alliance prior to 1/1/1816} 25 | #' \item{right_censor}{coded as (1) if the directed-dyad is still considered in the alliance as of 12/31/2012} 26 | #' \item{defense}{coded as (1) if ccode1 signed a defense pact to protect ccode2} 27 | #' \item{neutrality}{coded as (1) if ccode1 agreed to remain neutral toward ccode2} 28 | #' \item{nonaggression}{coded as (1) if ccode1 promised not to attack ccode2} 29 | #' \item{entente}{coded as (1) if ccode1 agreed to consult with ccode2 if a crisis occurred} 30 | #' \item{version}{version number of the data set (4.x)} 31 | #' } 32 | #' 33 | #' @references Gibler, Douglas M. 2009. International military alliances, 1648-2008. CQ Press. 34 | #' (\url{https://dmgibler.people.ua.edu/alliance-data.html}) 35 | #' 36 | #' @examples 37 | #' data(alliance) 38 | "alliance" 39 | 40 | -------------------------------------------------------------------------------- /R/apim.R: -------------------------------------------------------------------------------- 1 | #' @name apim 2 | #' @title actor-partner interdependence model 3 | #' 4 | #' will run the apim on indistinguishable dyads eventualy 5 | #' 6 | #' even more stuff about the apim 7 | #' 8 | #' @param x is a function with form y ~ x. 9 | #' @param dat is the dataframe. 10 | #' @param dyadid is a dyadic variable. 11 | #' @param option is to check whether dyad is indistingusihable. 12 | #' 13 | #' @details some additional details about these functions 14 | #' @import lazyeval 15 | 16 | #' @export 17 | apim <- function(x, dat, dyadid, option = "indistinguishable"){ 18 | 19 | if (lazyeval::is_formula(x)){ 20 | 21 | mod <- gls(x, na.action=na.omit, 22 | method="REML", verbose=TRUE, correlation=eval(parse(text=paste0("corCompSymm(form=~1|", dyadid, ")"))), 23 | data=dat) 24 | 25 | return(mod) 26 | 27 | }else { 28 | message("please enter a formula") 29 | } 30 | 31 | } 32 | 33 | globalVariables(c("gls","na.omit", "corCompSymm")) 34 | -------------------------------------------------------------------------------- /R/confintLME.R: -------------------------------------------------------------------------------- 1 | #' @name confintLME 2 | #' @title Confidence Intervals for LME Fixed Effects 3 | #' 4 | #' @param outp the lme model object. 5 | #' 6 | #' @details This function returns the confidence intervals in an organized fashion. 7 | #' @export 8 | #' 9 | confintLME <- function(outp){ 10 | 11 | rownames <- names(outp$coefficients$fixed) 12 | 13 | CI <- data.frame(intervals(outp, which = "fixed")$fixed[c(1: length(rownames)),c(1,3)], 14 | row.names = rownames) 15 | 16 | names(CI) <- c("2.5%", "97.5%") 17 | 18 | return(CI) 19 | } 20 | 21 | globalVariables(c("intervals")) 22 | -------------------------------------------------------------------------------- /R/counts_labels.R: -------------------------------------------------------------------------------- 1 | #' Counts the number of observations in each category of a variable that has 2 | #' value labels, returns counts and percent of total. 3 | #' @export 4 | #' @title counts_labels 5 | #' @param data a data.frame 6 | #' @param x a column in 'data'. Must be a string. 7 | #' @import dplyr 8 | counts_labels <- function(data, x) { 9 | if(!is.data.frame(data)) { 10 | stop("data.frame expected.") 11 | } 12 | if(is.factor(data[[x]])) { 13 | data[[x]] <- as.numeric(data[[x]]) 14 | cat("Factor converted to numeric.") 15 | } 16 | if(is.character(data[[x]])) { 17 | data[[x]] <- as.numeric(data[[x]]) 18 | cat("Factor converted to numeric.") 19 | } 20 | if(is.null(sjlabelled::get_labels(data[[x]]))) { 21 | stop(paste0("'", x, "' does not have value labels.")) 22 | } 23 | dims <- dim(data) 24 | counts <- data %>% 25 | select_(x) %>% 26 | group_by_(x) %>% 27 | count_() 28 | labels <- tibble::tibble(value_labels = 29 | get_labels(data[[x]])) 30 | labels <- rownames_to_column(labels, var = "rn") 31 | labels$rn <- as.numeric(labels[["rn"]]) 32 | names(counts)[1] <- "x" 33 | x_bins <- counts %>% 34 | right_join(labels, by = c("x" = "rn")) 35 | names(x_bins)[1] <- c(x, "n", "value_labels") 36 | x_bins[["n"]][is.na(x_bins[["n"]])] <- 0 37 | x_bins <- x_bins %>% 38 | mutate(percent = round((n / dims[[1]]) * 100)) 39 | return(x_bins) 40 | } 41 | 42 | globalVariables(c("get_labels","rownames_to_column")) 43 | -------------------------------------------------------------------------------- /R/crsp.R: -------------------------------------------------------------------------------- 1 | #' @name crsp 2 | #' @title Multiple Pseudo R-squared 3 | #' 4 | #' Get multiple R Squared 5 | #' 6 | #' 7 | #' @param esdmod is error standard deviation of the model of interest. 8 | #' @param esdemod is error standard deviation of the empty model. 9 | #' @param indistinguishable is to check whether the dyad is indistinguishable or not. 10 | #' 11 | #' 12 | #' @details some additional details about these functions 13 | #' @export 14 | # 15 | crsp = function (esdmod, esdemod, indistinguishable = TRUE) { 16 | if(indistinguishable){ 17 | rsq =1 - esdmod^2/esdemod^2 18 | if (rsq<0) rsq=0 19 | return(rsq) 20 | } 21 | # 22 | # if(!indistinguishable){ 23 | # rsq =1 - esdmod^2/esdemod^2 24 | # if (rsq<0) rsq=0 25 | # return(rsq) 26 | # } 27 | # 28 | } 29 | -------------------------------------------------------------------------------- /R/dyadic_trade-data.R: -------------------------------------------------------------------------------- 1 | #' Dyadic Trade Data 2 | #' 3 | #' Data from Correlates of War (COW) project in Version 3.0 4 | #' contains annual dyadic and national trade figures for states within the international system 5 | #' contains 139 years' data about dyadic trade 6 | #' 7 | #' @docType data 8 | #' 9 | #' @usage data(dyadic_trade) 10 | #' 11 | #' @format A data frame with 540,507 rows and 9 variables: 12 | #' \describe{ 13 | #' \item{ccode1}{Correlates of War Country Code for State A} 14 | #' \item{ccode2}{Correlates of War Country Code for State B} 15 | #' \item{year}{Observational Year} 16 | #' \item{importer1}{Name of country A} 17 | #' \item{importer2}{Name of country B} 18 | #' \item{flow1}{Imports of Country A from Country B in current US millions of dollars} 19 | #' \item{flow2}{Imports of Country B from Country A in current US millions of dollars} 20 | #' \item{source1}{Source of data for flow1 variable (see table below)} 21 | #' \item{source2}{Source of data for flow2 variable (see table below)} 22 | #' } 23 | #' 24 | #' @keywords datasets 25 | #' 26 | #' @references Correlates of War Version 3.0 27 | #' (\url{http://www.correlatesofwar.org/data-sets/bilateral-trade}) 28 | #' 29 | #' @examples 30 | #' data(dyadic_trade) 31 | #' \donttest{iplotCurve(flow1, flow2)} 32 | "dyadic_trade" 33 | 34 | 35 | -------------------------------------------------------------------------------- /R/getevd.R: -------------------------------------------------------------------------------- 1 | #' @name getevd 2 | #' @title Error standard deviation for distinguishable dyads 3 | #' 4 | #' Get error standard deviations from the distinguishable model with gls 5 | #' 6 | #' 7 | #' @param outp is the model object. Not it is not the "summary" of that object. 8 | #' @param tipe is the type of model object. It defaults to "gls." The other option is "lme." 9 | #' @param grp1 is the group 1 of the model object. For instance, grp1 is male. 10 | #' @param grp2 is the group 2 of the model object. For instance, grp2 is female. 11 | #' 12 | #' @details some additional details about these functions 13 | #' @export 14 | #' 15 | getevd = function (outp,tipe="gls",grp1="Group 1",grp2="Group 2") { 16 | vval=c(1,1) 17 | if (tipe=="gls") 18 | {ppp =outp[1]$modelStruct[2] 19 | vval[2] = as.numeric(outp[6]) 20 | vval[1] = vval[2]/attr(ppp$varStruct,"weights")[2]} 21 | if (tipe=="lme") 22 | {ppp =outp[1]$modelStruct$varStruct 23 | vval[2] = as.numeric(outp[6]) 24 | vval[1] = vval[2]/attr(ppp,"weights")[2]} 25 | names(vval)[1]=grp1 26 | names(vval)[2]=grp2 27 | return(vval)} 28 | -------------------------------------------------------------------------------- /R/graphMod.R: -------------------------------------------------------------------------------- 1 | #' @name graphMod 2 | #' @title Graph a Moderation Effect 3 | #' 4 | #' @param data the data. 5 | #' @param x the x variable given as data$x. 6 | #' @param y the y variable given as data$y. 7 | #' @param mod the moderator given as data$mod. 8 | #' @param highMod the model ran with HIGH_mod (can be gls or lme objects). 9 | #' @param lowMod the model ran with LOW_mod (can be gls or lme objects). 10 | #' @param int coefficient position of the y-intercept. 11 | #' @param slp coefficient position of the slope of x. 12 | #' @param hlab text label for "high" level of moderator. 13 | #' @param llab text label for "low" level of moderator. 14 | #' @import dplyr 15 | #' @import ggplot2 16 | #' 17 | #' @details This is function only works for numerical-numerical interactions. It returns a ggplot object. 18 | #' @export 19 | #' 20 | graphMod <- function(data, x, y, mod, highMod, lowMod, int, slp, hlab = "High", llab = "Low"){ 21 | 22 | d <- data %>% 23 | mutate(mod = mod, xvar = x, yvar = y) %>% 24 | dplyr::select(mod, xvar, yvar) %>% 25 | na.omit() %>% 26 | mutate(ModSplit = ifelse(mod >= mean(mod), 27 | hlab, llab)) 28 | 29 | if(class(highMod)=="gls"){ 30 | cc <- data.frame(slope = c(coef(lowMod)[slp], coef(highMod)[slp]), 31 | intercept = c(coef(lowMod)[int], coef(highMod)[int]), 32 | ModSplit = c(llab, hlab)) 33 | } 34 | 35 | if(class(highMod)=="lme"){ 36 | cc <- data.frame(slope = c(unlist(coef(lowMod)[slp])[1], unlist(coef(highMod)[slp])[1]), 37 | intercept = c(unlist(coef(lowMod)[int])[1], unlist(coef(highMod)[int])[1]), 38 | ModSplit = c(llab, hlab)) 39 | } 40 | 41 | plot <- ggplot(d, aes(x = xvar, y = yvar)) + 42 | geom_point(aes(group = ModSplit, 43 | color = ModSplit), 44 | alpha = .5) + 45 | geom_abline(data = cc, 46 | aes(intercept = intercept, 47 | slope = slope, 48 | color = ModSplit), 49 | size = 1) 50 | 51 | return(plot) 52 | } 53 | 54 | globalVariables(c("xvar","yvar","coef","ModSplit","intercept","slope")) 55 | -------------------------------------------------------------------------------- /R/lincomb.R: -------------------------------------------------------------------------------- 1 | #' @name lincomb 2 | #' @title Tests of contrasts 3 | #' 4 | #' Test the sum (S), the average (A), or the difference (D) of two effects from the same model. 5 | #' 6 | #' 7 | #' @param outp is the model object. For exmaple, summary(mod). It can be a gls or lme object. 8 | #' @param v1 is the number of the first effect. 9 | #' @param v2 is the number of the second effect. 10 | #' @param fun is the comparison. Default fun = "D". Other options include "S" the sum, and "A" the average. 11 | #' @importFrom stats pnorm 12 | #' @details some additional details about these functions 13 | #' @export 14 | #' 15 | # 16 | lincomb <- function(outp,v1,v2,fun="D"){ 17 | outp = summary(outp) 18 | 19 | vval = matrix() 20 | 21 | if(class(outp)[2]=="gls"){ 22 | c1=as.numeric(outp$coefficients[v1]) 23 | c2=as.numeric(outp$coefficients[v2]) 24 | 25 | cccov =outp$varBeta[v2,v1] 26 | } 27 | 28 | if(class(outp)[2]=="lme"){ 29 | c1=as.numeric(outp$coefficients$fixed[v1]) 30 | c2=as.numeric(outp$coefficients$fixed[v2]) 31 | 32 | cccov =outp$varFix[v2,v1] 33 | } 34 | 35 | c1se=outp$tTable[v1,2] 36 | c2se=outp$tTable[v2,2] 37 | 38 | if(fun=="A")vval[1]=(c1+c2)/2 39 | if(fun=="S")vval[1]=c1+c2 40 | if(fun=="D")vval[1]=c1-c2 41 | 42 | if(fun=="A")vval[2]=(c1se^2+c2se^2+2*cccov)/4 43 | if(fun=="S")vval[2]=c1se^2+c2se^2+2*cccov 44 | if(fun=="D")vval[2]=c1se^2+c2se^2-2*cccov 45 | 46 | vval[2]=sqrt(vval[2]) 47 | vval[3] = 2-2*pnorm(abs(vval[1]/vval[2])) 48 | 49 | return(vval) 50 | } -------------------------------------------------------------------------------- /R/mmc.R: -------------------------------------------------------------------------------- 1 | #' @name mmc 2 | #' @title Monte Carlo confidence interval for indirect effects 3 | #' 4 | #' @param a path from X to M. 5 | #' @param b path from M to Y. 6 | #' @param ase standard error for path a. 7 | #' @param bse standard error for path b. 8 | #' @param cov covariance for a and b (set to zero for MLM, but could be free if using lavaan). Defaults to zero. 9 | #' @param rep number of replications (defaults to 40,000). 10 | #' @param conf confidence level (defaults to 95). 11 | #' @param dig number of decimal places (defaults to 6) 12 | #' @param seed seed value (defaults to 12345) 13 | #' @importFrom MASS mvrnorm 14 | #' @importFrom stats quantile 15 | #' @details Base code taken from Selig and Preacher (2008). 16 | #' @export 17 | #' 18 | mmc<-function(a,b,ase,bse,cov = 0,rep = 40000,conf = 95, dig = 6, seed=12345) { 19 | 20 | 21 | pest <- c(a,b) 22 | 23 | acov <- matrix(c(ase^2,cov,cov,bse^2),2,2) 24 | set.seed(seed) 25 | mcmc <- mvrnorm(rep,pest,acov,empirical=FALSE) 26 | 27 | 28 | ab <- mcmc[,1]*mcmc[,2] 29 | 30 | cc=0 31 | for (ii in 1: rep) if (ab[ii] > 0) cc = cc + 1/rep 32 | 33 | low <- (1-conf/100)/2 34 | upp <- ((1-conf/100)/2)+(conf/100) 35 | 36 | LB <- format(quantile(ab,low),digits=dig) 37 | UB <- format(quantile(ab,upp),digits=dig) 38 | p_value = 1-2*abs(.5- cc) 39 | 40 | CI <- cbind.data.frame(LB, UB, p_value) 41 | rownames(CI)=paste0(low," to ",upp) 42 | return(CI) 43 | 44 | } -------------------------------------------------------------------------------- /R/smallsummary.R: -------------------------------------------------------------------------------- 1 | #' @name smallsummary 2 | #' @title Gives a Smaller Summary of gls and lme Objects 3 | #' 4 | #' @param outp the lme or gls model object. 5 | #' @importFrom stats confint 6 | #' @details This function returns the random effects (lme only), Rho, error variances, 7 | #' fixed effects, and their confidence intervals. It works for lme objects only. 8 | #' @export 9 | #' 10 | smallsummary <- function(outp){ 11 | 12 | if(class(outp) == "lme"){ 13 | print(summary(outp)$modelStruct$reStruct, sigma = summary(outp)$sigma) 14 | print(round(summary(outp)$tTable, 4)) 15 | cat("\n") 16 | CI <- round(confintLME(outp), 4) 17 | } 18 | 19 | if(class(outp) == "gls"){ 20 | 21 | is.distinguishable <- function(mod){ 22 | regexp_string <- "varIdent" 23 | str_detect(as.character(mod$call)[5], regexp_string) 24 | } 25 | 26 | if(is.distinguishable(outp)){ 27 | print(summary(outp)$modelStruct$corStruct) 28 | cat("\n") 29 | print(summary(outp)$modelStruct$varStruct) 30 | cat("Residual standard error:", summary(outp)$sigma, "\n") 31 | cat("\n") 32 | print(round(summary(outp)$tTable, 4)) 33 | cat("\n") 34 | 35 | CI <- round(confint(outp), 4) 36 | 37 | return(as.matrix(CI)) 38 | } 39 | 40 | print(summary(outp)$modelStruct$corStruct) 41 | cat("\n") 42 | cat("Residual standard error:", summary(outp)$sigma, "\n") 43 | cat("\n") 44 | print(round(summary(outp)$tTable, 4)) 45 | cat("\n") 46 | CI <- round(confint(outp), 4) 47 | 48 | } 49 | 50 | return(as.matrix(CI)) 51 | 52 | } 53 | -------------------------------------------------------------------------------- /R/sobel.R: -------------------------------------------------------------------------------- 1 | #' @name sobel 2 | #' @title Sobel Method for Testing Idirect Effects 3 | #' 4 | #' 5 | #' 6 | #' 7 | #' @param a path from X to M. 8 | #' @param b path from M to Y. 9 | #' @param ase standard error for path a. 10 | #' @param bse standard error for path b. 11 | #' @importFrom stats pnorm 12 | #' @details The Sobel method is conservative. Use the mmc function, or bootstrapping if marginal. The Sobel test also presumes a and b are uncorrelated. 13 | #' @export 14 | #' 15 | sobel <- function(a, b, ase, bse){ 16 | 17 | ab <- a*b 18 | ab_se <- sqrt(a^2*bse^2+b^2*ase^2) 19 | z <- ab/ab_se 20 | 21 | ifelse(ab > 0, p <- 2*pnorm(z, lower.tail=FALSE), p <- 2*pnorm(z)) 22 | 23 | return(data.frame(indirect_effect = ab, z_value = z, p_value = format(p, digits = 4, scientific = FALSE))) 24 | 25 | } -------------------------------------------------------------------------------- /R/testvar.R: -------------------------------------------------------------------------------- 1 | #' @name testvar 2 | #' @title Test the variance of a random effect 3 | #' 4 | #' @param ovar the outcome variable in quotes. 5 | #' @param xx string set of fixed variables separated by comma (program assumes two intercept). 6 | #' @param yy string set of random variables separated by comma (program assumes no intercept in the usual sense); last item on the list is tested (the first two arguments are the same here, but they do not have to be; there might be more items in the fixed part. 7 | #' @param dset the dataset. 8 | #' @param DID the dyad ID in quotes. 9 | #' @param obs the observation ID variable in quotes. This is a unique number for each dyad-measurement. 10 | #' @param dvv the distinguishing variable in quotes. 11 | #' @param ctrl an lmeControl object. Defaults to msMaxIter=10000, MaxIter=100000, msMaxEval=10000, returnObject=TRUE, niterEM=10000, nlmStepMax=1000. 12 | #' @importFrom stats pchisq 13 | #' @details Example call: testvar("AConflict","man,woman,MTime,WTime","man,woman,WTime,MTime",kashy_ppp,"DYADID","obsid", "GenderS"). 14 | #' @export 15 | #' 16 | testvar <- function(ovar, xx, yy, dset, DID, obs, dvv, ctrl = defaultctrl){ 17 | 18 | defaultctrl <- lmeControl(msMaxIter=10000, 19 | MaxIter=100000, 20 | msMaxEval=10000, 21 | returnObject=TRUE, 22 | niterEM=10000, 23 | nlmStepMax=1000) 24 | 25 | xxx= as.list(strsplit(xx, ",")[[1]]) 26 | basp=NULL 27 | basp=xxx[1] 28 | 29 | for(i in 1:length(xxx)) 30 | {if (i>1)basp =paste0(basp,"+",xxx[[i]])} 31 | 32 | basp=as.formula(paste0(ovar," ~ ",basp,"-1")) 33 | 34 | 35 | yyy= as.list(strsplit(yy, ",")[[1]]) 36 | bats=paste0(yyy[1]) 37 | pop=length(yyy)-1 38 | 39 | for(i in 1:pop) 40 | { 41 | if (i>1) 42 | { 43 | bats =paste0(bats,"+",yyy[[i]]) 44 | } 45 | } 46 | 47 | bats=paste0(bats,"-1") 48 | 49 | dset$DID=dset[,DID] 50 | dset$obs=dset[,obs] 51 | dset$dvv=dset[,dvv] 52 | rline=as.formula(paste0("random = ~ ",bats,"-1 |DID")) 53 | 54 | lll=yyy 55 | lll[length(yyy)]=NULL 56 | qq=as.formula(paste("~ ", paste(lll, collapse= "+"),paste("-1"))) 57 | pp=as.formula(paste("~ ", paste(yyy[4], collapse= "+"),paste("-1"))) 58 | 59 | 60 | fullrun=lme(basp, 61 | data = dset, 62 | rline, 63 | correlation = corCompSymm(form = ~1|DID/obs), 64 | weights = varIdent(form = ~1|dvv), 65 | na.action = na.omit, 66 | control = ctrl) 67 | 68 | 69 | parrun=lme(basp, 70 | data = dset, 71 | random= list(DID = pdBlocked(list(qq,pp))), 72 | correlation = corCompSymm(form = ~1|DID/obs), 73 | weights = varIdent(form = ~1|dvv), 74 | na.action = na.omit, 75 | control = ctrl) 76 | 77 | 78 | vvxx=NULL 79 | 80 | vvxx[3]= -2*logLik(fullrun)[1] +2*logLik(parrun)[1] 81 | 82 | 83 | 84 | vvxx[1]=ovar 85 | vvxx[2]=yyy[length(yyy)] 86 | vvxx[4]= 1 87 | vvxx[5] = {(pchisq(as.numeric(vvxx[3]), as.numeric(vvxx[4]), lower.tail=FALSE) 88 | + pchisq(as.numeric(vvxx[3]), as.numeric(vvxx[4])-1, lower.tail=FALSE))/2} 89 | 90 | names(vvxx) <- c("Outcome","Variance Component Tested","Chi Squared","df","p value") 91 | 92 | return(vvxx) 93 | 94 | } 95 | 96 | globalVariables(c("lme")) -------------------------------------------------------------------------------- /R/var_labels.R: -------------------------------------------------------------------------------- 1 | #' Creates a `tbl_df` that contains the column names and variable labels to 2 | #' easily explore the data. 3 | #' @export 4 | #' @title var_labels 5 | #' @param data a data.frame 6 | var_labels <- function(data) { 7 | if(!is.data.frame(data)){ 8 | stop("data.frame expected.") 9 | } 10 | if(all(sjlabelled::get_label(data) == "")) { 11 | stop("Data does not have any variable labels.") 12 | } 13 | var_labels <- tibble::tibble(column_name = colnames(data), 14 | variable_label = sjlabelled::get_label(data)) 15 | } 16 | -------------------------------------------------------------------------------- /R/variable_view.R: -------------------------------------------------------------------------------- 1 | #' @name variable_view 2 | #' @title Variable names with labels like in SPSS 3 | #' 4 | #' @param data the lme model object. 5 | #' 6 | #' @details Example call: variable_view(acipair) 7 | #' @export 8 | #' 9 | variable_view <- function(data){ 10 | my.list = list() 11 | 12 | for (i in names(data)){ 13 | #if the label is numeric then it's a "labels"; if it's null then it has neither a label or labels 14 | label = (c(i, ifelse(is.numeric(attr(data[[as.name(i)]],"label")) | is.null(attr(data[[as.name(i)]],"label")), 15 | NA, 16 | attr(data[[as.name(i)]],"label")))) 17 | my.list[[i]] = label 18 | } 19 | 20 | attributes = data.frame(matrix(unlist(my.list),ncol = 2,byrow = TRUE)) 21 | 22 | colnames(attributes)[1] <- "variable" 23 | colnames(attributes)[2] <- "label" 24 | 25 | return(attributes) 26 | } -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | output: github_document 3 | --- 4 | 5 | 6 | 7 | ```{r, include = FALSE} 8 | knitr::opts_chunk$set( 9 | collapse = TRUE, 10 | comment = "#>", 11 | fig.path = "man/figures/README-", 12 | out.width = "100%" 13 | ) 14 | ``` 15 | 16 | # dyadr 17 | [![Travis-CI Build Status](https://api.travis-ci.org/abarylsky/dyadr.svg?branch=master)](https://travis-ci.org/abarylsky/dyadr) 18 | 19 | 20 | r package for dyadic data analysis 21 | 22 | # Description 23 | An R package for assisting people in dyadic data analysis. Contains functions to organize output from the `gls` and `lme` functions from the `nlme` package for cross-sectional data. Some functionality exists with the `lme4` package. Improves user understanding of the Actor-Partner Independence Model by organizing actor and parter effects for the purpose of comparing parameters to each other. 24 | 25 | # Installation 26 | ```{r, eval=FALSE} 27 | # install.packages("devtools") 28 | devtools::install_github("RandiLGarcia/dyadr") 29 | ``` 30 | 31 | # Usage 32 | 33 | Here is an example of how to use some of the `dyadr` functions. 34 | 35 | First, load the package and get data: 36 | ```{r, warning = FALSE} 37 | library(nlme) 38 | library(dyadr) 39 | ``` 40 | 41 | Using the `smallsummary` function 42 | 43 | ```{r} 44 | apim <- gls(Satisfaction_A ~ Tension_A + SelfPos_P, 45 | na.action = na.omit, 46 | correlation = corCompSymm(form = ~ 1 | CoupleID), 47 | data = acipair 48 | ) 49 | 50 | smallsummary(apim) 51 | ``` 52 | 53 | Using the `crsp` function 54 | 55 | ```{r} 56 | # Empty Model 57 | apimie <- summary(gls(Satisfaction_A ~ 1, 58 | na.action = na.omit, 59 | correlation = corCompSymm(form = ~ 1 | CoupleID), 60 | data = acipair 61 | )) 62 | # sd of errors for the model or esd 63 | esd <- as.numeric(apim[6]) 64 | # sd of errors for the empty model or esd0 65 | esd0 <- as.numeric(apimie[6]) 66 | # the R squared, using the crsp function 67 | crsp(esd, esd0) 68 | ``` 69 | 70 | # Contributing 71 | Feel free to submit pull requests resolving documented issues. 72 | 73 | # Authors 74 | * **Randi L. Garcia** - *Initial work* - [dyadr](https://github.com/RandiLGarcia/dyadr) 75 | * **David A. Kenny** - *Initial work* 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # dyadr 5 | 6 | [![Travis-CI Build 7 | Status](https://api.travis-ci.org/abarylsky/dyadr.svg?branch=master)](https://travis-ci.org/abarylsky/dyadr) 8 | 9 | r package for dyadic data analysis 10 | 11 | # Description 12 | 13 | An R package for assisting people in dyadic data analysis. Contains 14 | functions to organize output from the `gls` and `lme` functions from the 15 | `nlme` package for cross-sectional data. Some functionality exists with 16 | the `lme4` package. Improves user understanding of the Actor-Partner 17 | Independence Model by organizing actor and parter effects for the 18 | purpose of comparing parameters to each other. 19 | 20 | # Installation 21 | 22 | ``` r 23 | # install.packages("devtools") 24 | devtools::install_github("RandiLGarcia/dyadr") 25 | ``` 26 | 27 | # Usage 28 | 29 | Here is an example of how to use some of the `dyadr` functions. 30 | 31 | First, load the package and get data: 32 | 33 | ``` r 34 | library(nlme) 35 | library(dyadr) 36 | ``` 37 | 38 | Using the `smallsummary` function 39 | 40 | ``` r 41 | apim <- gls(Satisfaction_A ~ Tension_A + SelfPos_P, 42 | na.action = na.omit, 43 | correlation = corCompSymm(form = ~ 1 | CoupleID), 44 | data = acipair 45 | ) 46 | 47 | smallsummary(apim) 48 | #> Correlation structure of class corCompSymm representing 49 | #> Rho 50 | #> 0.4715039 51 | #> 52 | #> Residual standard error: 0.4052903 53 | #> 54 | #> Value Std.Error t-value p-value 55 | #> (Intercept) 4.7190 0.2366 19.9475 0.0000 56 | #> Tension_A -0.3454 0.0329 -10.5032 0.0000 57 | #> SelfPos_P -0.0656 0.0516 -1.2716 0.2045 58 | #> 2.5 % 97.5 % 59 | #> (Intercept) 4.2553 5.1827 60 | #> Tension_A -0.4099 -0.2810 61 | #> SelfPos_P -0.1667 0.0355 62 | ``` 63 | 64 | Using the `crsp` function 65 | 66 | ``` r 67 | # Empty Model 68 | apimie <- summary(gls(Satisfaction_A ~ 1, 69 | na.action = na.omit, 70 | correlation = corCompSymm(form = ~ 1 | CoupleID), 71 | data = acipair 72 | )) 73 | # sd of errors for the model or esd 74 | esd <- as.numeric(apim[6]) 75 | # sd of errors for the empty model or esd0 76 | esd0 <- as.numeric(apimie[6]) 77 | # the R squared, using the crsp function 78 | crsp(esd, esd0) 79 | #> [1] 0.3348468 80 | ``` 81 | 82 | # Contributing 83 | 84 | Feel free to submit pull requests resolving documented issues. 85 | 86 | # Authors 87 | 88 | - **Randi L. Garcia** - *Initial work* - 89 | [dyadr](https://github.com/RandiLGarcia/dyadr) 90 | - **David A. Kenny** - *Initial work* 91 | -------------------------------------------------------------------------------- /data/acipair.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RandiLGarcia/dyadr/5d317dceb2e278887b9684e172bd79a0c12974af/data/acipair.RData -------------------------------------------------------------------------------- /data/alliance.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RandiLGarcia/dyadr/5d317dceb2e278887b9684e172bd79a0c12974af/data/alliance.rda -------------------------------------------------------------------------------- /data/dyadic_trade.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RandiLGarcia/dyadr/5d317dceb2e278887b9684e172bd79a0c12974af/data/dyadic_trade.rda -------------------------------------------------------------------------------- /dyadr.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | BuildType: Package 16 | PackageUseDevtools: Yes 17 | PackageInstallArgs: --no-multiarch --with-keep.source 18 | PackageRoxygenize: rd,collate,namespace 19 | -------------------------------------------------------------------------------- /man/LRtestvar.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/LRtestvar.R 3 | \name{LRtestvar} 4 | \alias{LRtestvar} 5 | \title{Test the variance of a random effect} 6 | \usage{ 7 | LRtestvar(outp, p, ctrl = defaultctrl) 8 | } 9 | \arguments{ 10 | \item{outp}{the lme model object.} 11 | 12 | \item{p}{string variable that you want to test the random variance component for.} 13 | 14 | \item{ctrl}{an lmeControl object. Defaults to msMaxIter=10000, MaxIter=100000, msMaxEval=10000, returnObject=TRUE, niterEM=10000, nlmStepMax=1000.} 15 | } 16 | \description{ 17 | Test the variance of a random effect 18 | } 19 | \details{ 20 | LRtestvar(dyadGC_full, "MTime") 21 | } 22 | -------------------------------------------------------------------------------- /man/acipair.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/acipair-data.R 3 | \docType{data} 4 | \name{acipair} 5 | \alias{acipair} 6 | \title{Acitelli Data} 7 | \format{ 8 | An object of class \code{"cross"}; see \code{\link[qtl]{read.cross}}. 9 | } 10 | \usage{ 11 | data(acipair) 12 | } 13 | \description{ 14 | Data from 148 heterosexual married couples in Detroit 15 | } 16 | \examples{ 17 | data(acipair) 18 | \donttest{iplotCurves(phe, times)} 19 | } 20 | \keyword{datasets} 21 | -------------------------------------------------------------------------------- /man/alliance.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/alliance-data.R 3 | \docType{data} 4 | \name{alliance} 5 | \alias{alliance} 6 | \title{Alliance Data} 7 | \format{ 8 | A data frame with 3252 rows and 18 variables: 9 | \describe{ 10 | \item{version4id}{the unique serial identification number for each alliance} 11 | \item{ccode1}{the Correlates of War System Membership number of the state initiating alliance terms toward ccode2} 12 | \item{state_name1}{the Correlates of War System Membership name of ccode1} 13 | \item{ccode2}{the Correlates of War System Membership number of the state receiving alliance terms from ccode1} 14 | \item{state_name2}{the Correlates of War System Membership name of ccode2} 15 | \item{dyad_st_day}{the day of entry into the Correlates of War system for the allied dyad} 16 | \item{dyad_st_month}{the month of entry into the Correlates of War system for the allied dyad} 17 | \item{dyad_st_year}{the year of entry into the Correlates of War system for the allied dyad} 18 | \item{dyad_end_day}{the day of alliance entry for the directed-dyad observation; missing data denotes alliance is still in effect as of 12/31/2012} 19 | \item{dyad_end_month}{the month of alliance entry for the directed-dyad observation; missing data denotes alliance is still in effect as of 12/31/2012} 20 | \item{dyad_end_year}{the year of alliance entry for the directed-dyad observation; missing data denotes alliance is still in effect as of 12/31/2012} 21 | \item{left_censor}{coded as (1) if the directed-dyad entered the alliance prior to 1/1/1816} 22 | \item{right_censor}{coded as (1) if the directed-dyad is still considered in the alliance as of 12/31/2012} 23 | \item{defense}{coded as (1) if ccode1 signed a defense pact to protect ccode2} 24 | \item{neutrality}{coded as (1) if ccode1 agreed to remain neutral toward ccode2} 25 | \item{nonaggression}{coded as (1) if ccode1 promised not to attack ccode2} 26 | \item{entente}{coded as (1) if ccode1 agreed to consult with ccode2 if a crisis occurred} 27 | \item{version}{version number of the data set (4.x)} 28 | } 29 | } 30 | \usage{ 31 | data(alliance) 32 | } 33 | \description{ 34 | Data from Gibler (2009) paper about International military alliances contains the alliance dataset distributed by directed-dyad, with one observation for each directed-dyad alliance initiation, with data on 414 countries. 35 | } 36 | \examples{ 37 | data(alliance) 38 | } 39 | \references{ 40 | Gibler, Douglas M. 2009. International military alliances, 1648-2008. CQ Press. 41 | (\url{https://dmgibler.people.ua.edu/alliance-data.html}) 42 | } 43 | \keyword{datasets} 44 | -------------------------------------------------------------------------------- /man/apim.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/apim.R 3 | \name{apim} 4 | \alias{apim} 5 | \title{actor-partner interdependence model 6 | 7 | will run the apim on indistinguishable dyads eventualy 8 | 9 | even more stuff about the apim} 10 | \usage{ 11 | apim(x, dat, dyadid, option = "indistinguishable") 12 | } 13 | \arguments{ 14 | \item{x}{is a function with form y ~ x.} 15 | 16 | \item{dat}{is the dataframe.} 17 | 18 | \item{dyadid}{is a dyadic variable.} 19 | 20 | \item{option}{is to check whether dyad is indistingusihable.} 21 | } 22 | \description{ 23 | actor-partner interdependence model 24 | 25 | will run the apim on indistinguishable dyads eventualy 26 | 27 | even more stuff about the apim 28 | } 29 | \details{ 30 | some additional details about these functions 31 | } 32 | -------------------------------------------------------------------------------- /man/confintLME.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/confintLME.R 3 | \name{confintLME} 4 | \alias{confintLME} 5 | \title{Confidence Intervals for LME Fixed Effects} 6 | \usage{ 7 | confintLME(outp) 8 | } 9 | \arguments{ 10 | \item{outp}{the lme model object.} 11 | } 12 | \description{ 13 | Confidence Intervals for LME Fixed Effects 14 | } 15 | \details{ 16 | This function returns the confidence intervals in an organized fashion. 17 | } 18 | -------------------------------------------------------------------------------- /man/counts_labels.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/counts_labels.R 3 | \name{counts_labels} 4 | \alias{counts_labels} 5 | \title{counts_labels} 6 | \usage{ 7 | counts_labels(data, x) 8 | } 9 | \arguments{ 10 | \item{data}{a data.frame} 11 | 12 | \item{x}{a column in 'data'. Must be a string.} 13 | } 14 | \description{ 15 | Counts the number of observations in each category of a variable that has 16 | value labels, returns counts and percent of total. 17 | } 18 | -------------------------------------------------------------------------------- /man/crsp.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/crsp.R 3 | \name{crsp} 4 | \alias{crsp} 5 | \title{Multiple Pseudo R-squared 6 | 7 | Get multiple R Squared} 8 | \usage{ 9 | crsp(esdmod, esdemod, indistinguishable = TRUE) 10 | } 11 | \arguments{ 12 | \item{esdmod}{is error standard deviation of the model of interest.} 13 | 14 | \item{esdemod}{is error standard deviation of the empty model.} 15 | 16 | \item{indistinguishable}{is to check whether the dyad is indistinguishable or not.} 17 | } 18 | \description{ 19 | Multiple Pseudo R-squared 20 | 21 | Get multiple R Squared 22 | } 23 | \details{ 24 | some additional details about these functions 25 | } 26 | -------------------------------------------------------------------------------- /man/dyadic_trade.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/dyadic_trade-data.R 3 | \docType{data} 4 | \name{dyadic_trade} 5 | \alias{dyadic_trade} 6 | \title{Dyadic Trade Data} 7 | \format{ 8 | A data frame with 540,507 rows and 9 variables: 9 | \describe{ 10 | \item{ccode1}{Correlates of War Country Code for State A} 11 | \item{ccode2}{Correlates of War Country Code for State B} 12 | \item{year}{Observational Year} 13 | \item{importer1}{Name of country A} 14 | \item{importer2}{Name of country B} 15 | \item{flow1}{Imports of Country A from Country B in current US millions of dollars} 16 | \item{flow2}{Imports of Country B from Country A in current US millions of dollars} 17 | \item{source1}{Source of data for flow1 variable (see table below)} 18 | \item{source2}{Source of data for flow2 variable (see table below)} 19 | } 20 | } 21 | \usage{ 22 | data(dyadic_trade) 23 | } 24 | \description{ 25 | Data from Correlates of War (COW) project in Version 3.0 26 | contains annual dyadic and national trade figures for states within the international system 27 | contains 139 years' data about dyadic trade 28 | } 29 | \examples{ 30 | data(dyadic_trade) 31 | \donttest{iplotCurve(flow1, flow2)} 32 | } 33 | \references{ 34 | Correlates of War Version 3.0 35 | (\url{http://www.correlatesofwar.org/data-sets/bilateral-trade}) 36 | } 37 | \keyword{datasets} 38 | -------------------------------------------------------------------------------- /man/getevd.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getevd.R 3 | \name{getevd} 4 | \alias{getevd} 5 | \title{Error standard deviation for distinguishable dyads 6 | 7 | Get error standard deviations from the distinguishable model with gls} 8 | \usage{ 9 | getevd(outp, tipe = "gls", grp1 = "Group 1", grp2 = "Group 2") 10 | } 11 | \arguments{ 12 | \item{outp}{is the model object. Not it is not the "summary" of that object.} 13 | 14 | \item{tipe}{is the type of model object. It defaults to "gls." The other option is "lme."} 15 | 16 | \item{grp1}{is the group 1 of the model object. For instance, grp1 is male.} 17 | 18 | \item{grp2}{is the group 2 of the model object. For instance, grp2 is female.} 19 | } 20 | \description{ 21 | Error standard deviation for distinguishable dyads 22 | 23 | Get error standard deviations from the distinguishable model with gls 24 | } 25 | \details{ 26 | some additional details about these functions 27 | } 28 | -------------------------------------------------------------------------------- /man/graphMod.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/graphMod.R 3 | \name{graphMod} 4 | \alias{graphMod} 5 | \title{Graph a Moderation Effect} 6 | \usage{ 7 | graphMod( 8 | data, 9 | x, 10 | y, 11 | mod, 12 | highMod, 13 | lowMod, 14 | int, 15 | slp, 16 | hlab = "High", 17 | llab = "Low" 18 | ) 19 | } 20 | \arguments{ 21 | \item{data}{the data.} 22 | 23 | \item{x}{the x variable given as data$x.} 24 | 25 | \item{y}{the y variable given as data$y.} 26 | 27 | \item{mod}{the moderator given as data$mod.} 28 | 29 | \item{highMod}{the model ran with HIGH_mod (can be gls or lme objects).} 30 | 31 | \item{lowMod}{the model ran with LOW_mod (can be gls or lme objects).} 32 | 33 | \item{int}{coefficient position of the y-intercept.} 34 | 35 | \item{slp}{coefficient position of the slope of x.} 36 | 37 | \item{hlab}{text label for "high" level of moderator.} 38 | 39 | \item{llab}{text label for "low" level of moderator.} 40 | } 41 | \description{ 42 | Graph a Moderation Effect 43 | } 44 | \details{ 45 | This is function only works for numerical-numerical interactions. It returns a ggplot object. 46 | } 47 | -------------------------------------------------------------------------------- /man/lincomb.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/lincomb.R 3 | \name{lincomb} 4 | \alias{lincomb} 5 | \title{Tests of contrasts 6 | 7 | Test the sum (S), the average (A), or the difference (D) of two effects from the same model.} 8 | \usage{ 9 | lincomb(outp, v1, v2, fun = "D") 10 | } 11 | \arguments{ 12 | \item{outp}{is the model object. For exmaple, summary(mod). It can be a gls or lme object.} 13 | 14 | \item{v1}{is the number of the first effect.} 15 | 16 | \item{v2}{is the number of the second effect.} 17 | 18 | \item{fun}{is the comparison. Default fun = "D". Other options include "S" the sum, and "A" the average.} 19 | } 20 | \description{ 21 | Tests of contrasts 22 | 23 | Test the sum (S), the average (A), or the difference (D) of two effects from the same model. 24 | } 25 | \details{ 26 | some additional details about these functions 27 | } 28 | -------------------------------------------------------------------------------- /man/mmc.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mmc.R 3 | \name{mmc} 4 | \alias{mmc} 5 | \title{Monte Carlo confidence interval for indirect effects} 6 | \usage{ 7 | mmc(a, b, ase, bse, cov = 0, rep = 40000, conf = 95, dig = 6, seed = 12345) 8 | } 9 | \arguments{ 10 | \item{a}{path from X to M.} 11 | 12 | \item{b}{path from M to Y.} 13 | 14 | \item{ase}{standard error for path a.} 15 | 16 | \item{bse}{standard error for path b.} 17 | 18 | \item{cov}{covariance for a and b (set to zero for MLM, but could be free if using lavaan). Defaults to zero.} 19 | 20 | \item{rep}{number of replications (defaults to 40,000).} 21 | 22 | \item{conf}{confidence level (defaults to 95).} 23 | 24 | \item{dig}{number of decimal places (defaults to 6)} 25 | 26 | \item{seed}{seed value (defaults to 12345)} 27 | } 28 | \description{ 29 | Monte Carlo confidence interval for indirect effects 30 | } 31 | \details{ 32 | Base code taken from Selig and Preacher (2008). 33 | } 34 | -------------------------------------------------------------------------------- /man/smallsummary.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/smallsummary.R 3 | \name{smallsummary} 4 | \alias{smallsummary} 5 | \title{Gives a Smaller Summary of gls and lme Objects} 6 | \usage{ 7 | smallsummary(outp) 8 | } 9 | \arguments{ 10 | \item{outp}{the lme or gls model object.} 11 | } 12 | \description{ 13 | Gives a Smaller Summary of gls and lme Objects 14 | } 15 | \details{ 16 | This function returns the random effects (lme only), Rho, error variances, 17 | fixed effects, and their confidence intervals. It works for lme objects only. 18 | } 19 | -------------------------------------------------------------------------------- /man/sobel.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sobel.R 3 | \name{sobel} 4 | \alias{sobel} 5 | \title{Sobel Method for Testing Idirect Effects} 6 | \usage{ 7 | sobel(a, b, ase, bse) 8 | } 9 | \arguments{ 10 | \item{a}{path from X to M.} 11 | 12 | \item{b}{path from M to Y.} 13 | 14 | \item{ase}{standard error for path a.} 15 | 16 | \item{bse}{standard error for path b.} 17 | } 18 | \description{ 19 | Sobel Method for Testing Idirect Effects 20 | } 21 | \details{ 22 | The Sobel method is conservative. Use the mmc function, or bootstrapping if marginal. The Sobel test also presumes a and b are uncorrelated. 23 | } 24 | -------------------------------------------------------------------------------- /man/testvar.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testvar.R 3 | \name{testvar} 4 | \alias{testvar} 5 | \title{Test the variance of a random effect} 6 | \usage{ 7 | testvar(ovar, xx, yy, dset, DID, obs, dvv, ctrl = defaultctrl) 8 | } 9 | \arguments{ 10 | \item{ovar}{the outcome variable in quotes.} 11 | 12 | \item{xx}{string set of fixed variables separated by comma (program assumes two intercept).} 13 | 14 | \item{yy}{string set of random variables separated by comma (program assumes no intercept in the usual sense); last item on the list is tested (the first two arguments are the same here, but they do not have to be; there might be more items in the fixed part.} 15 | 16 | \item{dset}{the dataset.} 17 | 18 | \item{DID}{the dyad ID in quotes.} 19 | 20 | \item{obs}{the observation ID variable in quotes. This is a unique number for each dyad-measurement.} 21 | 22 | \item{dvv}{the distinguishing variable in quotes.} 23 | 24 | \item{ctrl}{an lmeControl object. Defaults to msMaxIter=10000, MaxIter=100000, msMaxEval=10000, returnObject=TRUE, niterEM=10000, nlmStepMax=1000.} 25 | } 26 | \description{ 27 | Test the variance of a random effect 28 | } 29 | \details{ 30 | Example call: testvar("AConflict","man,woman,MTime,WTime","man,woman,WTime,MTime",kashy_ppp,"DYADID","obsid", "GenderS"). 31 | } 32 | -------------------------------------------------------------------------------- /man/var_labels.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/var_labels.R 3 | \name{var_labels} 4 | \alias{var_labels} 5 | \title{var_labels} 6 | \usage{ 7 | var_labels(data) 8 | } 9 | \arguments{ 10 | \item{data}{a data.frame} 11 | } 12 | \description{ 13 | Creates a `tbl_df` that contains the column names and variable labels to 14 | easily explore the data. 15 | } 16 | -------------------------------------------------------------------------------- /man/variable_view.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/variable_view.R 3 | \name{variable_view} 4 | \alias{variable_view} 5 | \title{Variable names with labels like in SPSS} 6 | \usage{ 7 | variable_view(data) 8 | } 9 | \arguments{ 10 | \item{data}{the lme model object.} 11 | } 12 | \description{ 13 | Variable names with labels like in SPSS 14 | } 15 | \details{ 16 | Example call: variable_view(acipair) 17 | } 18 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(dyadr) 3 | 4 | test_check("dyadr") 5 | -------------------------------------------------------------------------------- /tests/testthat/test_dyadr.R: -------------------------------------------------------------------------------- 1 | context("dyadr") 2 | 3 | test_that("var_labels error works", { 4 | expect_error(var_labels(iris), "labels")}) 5 | 6 | test_that("apim error works", { 7 | expect_message(apim("x"), "please enter a formula")}) 8 | 9 | test_that("crsp output returns correct value", { 10 | if (require(nlme)) { 11 | apimi = gls(Satisfaction_A ~ Tension_A + SelfPos_P, 12 | na.action=na.omit, 13 | correlation=corCompSymm (form=~1|CoupleID), 14 | data=acipair) 15 | apimie = summary(gls(Satisfaction_A ~ 1, 16 | na.action=na.omit, 17 | correlation=corCompSymm (form=~1|CoupleID), 18 | data=acipair)) 19 | # sd of errors for the model or esd 20 | esd = as.numeric(apimi[6]) 21 | # sd of errors for the empty model or esd0 22 | esd0 = as.numeric(apimie[6]) 23 | # the R squared, using the crsp function 24 | print(crsp(esd, esd0)) 25 | expect_gt(crsp(esd,esd0),0.3) 26 | } 27 | }) 28 | 29 | test_that("smallsummary returns output including Correlation", { 30 | apimi = nlme::gls(Satisfaction_A ~ Tension_A + SelfPos_P, 31 | na.action=na.omit, 32 | correlation=corCompSymm (form=~1|CoupleID), 33 | data=acipair) 34 | expect_output(smallsummary(apimi), "Correlation")}) 35 | 36 | test_that("counts_labels error works", { 37 | expect_error(counts_labels(acipair, x = "SelfPos_P"), "'SelfPos_P' does not have value labels.") 38 | }) 39 | 40 | 41 | test_that("lincomb works", { 42 | apimi = nlme::gls(Satisfaction_A ~ Tension_A + SelfPos_P, 43 | na.action=na.omit, 44 | correlation=corCompSymm (form=~1|CoupleID), 45 | data=acipair) 46 | expect_length(lincomb(apimi, 2, 3), 3) 47 | }) 48 | 49 | test_that("variable_view has correct length", { 50 | expect_length(variable_view(dyadic_trade), 2) 51 | }) -------------------------------------------------------------------------------- /vignettes/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | *.R 3 | -------------------------------------------------------------------------------- /vignettes/dyadr_vignette.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "dyadr_vignette" 3 | output: rmarkdown::html_vignette 4 | vignette: > 5 | %\VignetteIndexEntry{dyadr_vignette} 6 | %\VignetteEngine{knitr::rmarkdown} 7 | %\VignetteEncoding{UTF-8} 8 | --- 9 | 10 | ```{r, include = FALSE} 11 | knitr::opts_chunk$set( 12 | collapse = TRUE, 13 | comment = "#>", 14 | fig.path = "README-" 15 | ) 16 | ``` 17 | 18 | 19 | # Examples 20 | 21 | Here is an example of how to use some of the `dyadr` functions. 22 | 23 | ```{r} 24 | library(nlme) 25 | library(dyadr) 26 | ``` 27 | 28 | Using the `apim` function 29 | ```{r} 30 | apim("x") 31 | ``` 32 | 33 | Using the `smallsummary` function 34 | 35 | ```{r} 36 | apimi <- gls(Satisfaction_A ~ Tension_A + SelfPos_P, 37 | na.action = na.omit, 38 | correlation = corCompSymm(form = ~ 1 | CoupleID), 39 | data = acipair 40 | ) 41 | 42 | smallsummary(apimi) 43 | ``` 44 | 45 | Using the `crsp` function 46 | 47 | ```{r} 48 | # Empty Model 49 | apimie <- summary(gls(Satisfaction_A ~ 1, 50 | na.action = na.omit, 51 | correlation = corCompSymm(form = ~ 1 | CoupleID), 52 | data = acipair 53 | )) 54 | # sd of errors for the model or esd 55 | esd <- as.numeric(apimi[6]) 56 | # sd of errors for the empty model or esd0 57 | esd0 <- as.numeric(apimie[6]) 58 | # the R squared, using the crsp function 59 | crsp(esd, esd0) 60 | ``` 61 | 62 | Using the `lincomb` function 63 | 64 | ```{r} 65 | apimi <- nlme::gls(Satisfaction_A ~ Tension_A + SelfPos_P, 66 | na.action = na.omit, 67 | correlation = corCompSymm(form = ~ 1 | CoupleID), 68 | data = acipair 69 | ) 70 | lincomb(apimi, 2, 3) 71 | ``` 72 | 73 | Using `variable_view` function 74 | 75 | ```{r} 76 | variable_view(dyadic_trade) 77 | ``` 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | --------------------------------------------------------------------------------