FreesearchR/man/wide2long.Rd

64 lines
1.8 KiB
Text
Raw Permalink Normal View History

2025-03-11 13:42:57 +01:00
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/wide2long.R
\name{wide2long}
\alias{wide2long}
\title{Alternative pivoting method for easily pivoting based on name pattern}
\usage{
wide2long(
data,
pattern,
type = c("prefix", "infix", "suffix"),
id.col = 1,
instance.name = "instance"
)
}
\arguments{
\item{data}{data}
\item{pattern}{pattern(s) to match. Character vector of length 1 or more.}
\item{type}{type of match. can be one of "prefix","infix" or "suffix".}
\item{id.col}{ID column. Will fill ID for all. Column name or numeric index.
Default is "1", first column.}
\item{instance.name}{}
}
\value{
data.frame
}
\description{
This function requires and assumes a systematic naming of variables.
For now only supports one level pivoting. Adding more levels would require
an added "ignore" string pattern or similarly. Example 2.
}
\examples{
data.frame(
1:20, sample(70:80, 20, TRUE),
sample(70:100, 20, TRUE),
sample(70:100, 20, TRUE),
sample(170:200, 20, TRUE)
) |>
setNames(c("id", "age", "weight_0", "weight_1", "height_1")) |>
wide2long(pattern = c("_0", "_1"), type = "suffix")
data.frame(
1:20, sample(70:80, 20, TRUE),
sample(70:100, 20, TRUE),
sample(70:100, 20, TRUE),
sample(170:200, 20, TRUE)
) |>
setNames(c("id", "age", "weight_0", "weight_a_1", "height_b_1")) |>
wide2long(pattern = c("_0", "_1"), type = "suffix")
# Optional filling of missing values by last observation carried forward
# Needed for mmrm analyses
long_missings |>
# Fills record ID assuming none are missing
tidyr::fill(record_id) |>
# Grouping by ID for the last step
dplyr::group_by(record_id) |>
# Filling missing data by ID
tidyr::fill(names(long_missings)[!names(long_missings) \%in\% new_names]) |>
# Remove grouping
dplyr::ungroup()
}