knitr::opts_chunk$set( collapse = TRUE, comment = "##", fig.width = 8, fig.height = 5.5, out.width = "90%" ) library(tidyverse) library(viridisLite) library(SemiPar) library(gridExtra) theme_set(theme_minimal() + theme(legend.position = "bottom")) options( ggplot2.continuous.colour = "viridis", ggplot2.continuous.fill = "viridis" ) scale_colour_discrete <- scale_colour_viridis_d scale_fill_discrete <- scale_fill_viridis_d library("tidyfun") pal_5 <- viridis(7)[-(1:2)] set.seed(1221)
Functional data have often been stored in matrices or data frames. Although these structures have sufficed for some purposes, they are cumbersome or impossible to use with modern tools for data wrangling.
In this vignette, we illustrate how to convert data from common structures to tf
objects. Throughout, functional data vectors are stored as columns in a data frame to facilitate subsequent wrangling and analysis.
One of the most common structures for storing functional data has been a matrix. Especially when subjects are observed over the same (regular or irregular) grid, it is natural to observations on a subject in rows (or columns) of a matrix. Matrices, however, are difficult to wrangle along with data in a data frame, leading to confusing and easy-to-break subsetting across several objects.
In the following examples, we'll use tfd
to get a tf
vector from matrices. The tfd
function expects data to be organized so that each row is the functional observation for a single subject. It's possible to focus only on the resulting tf
vector, but in keeping with the broader goals of tidyfun
we'll add these as columns to a data frame.
The DTI
data in the refund
package has been a popular example in functional data analysis. In the code below, we create a data frame (or tibble
) containing scalar covariates, and then add columns for the cca
and rcst
track profiles. This code was used to create the tidyfun::dti_df
dataset included in the package.
dti_df <- tibble( id = refund::DTI$ID, visit = refund::DTI$visit, sex = refund::DTI$sex, case = factor(ifelse(refund::DTI$case, "MS", "control")) ) dti_df$cca <- tfd(refund::DTI$cca, arg = seq(0, 1, length.out = 93)) dti_df$rcst <- tfd(refund::DTI$rcst, arg = seq(0, 1, length.out = 55))
In tfd
, the first argument is a matrix; arg
defines the grid over which functions are observed. The output of tfd
is a vector, which we include in the dti_df
data frame.
dti_df
Finally, we'll make a quick spaghetti plot to illustrate that the complete functional data is included in each tf
column.
dti_df |> ggplot() + geom_spaghetti(aes(y = cca, col = case, alpha = 0.2 + 0.4 * (case == "control"))) + facet_wrap(~sex) + scale_alpha(guide = "none", range = c(0.2, 0.4))
We'll repeat the same basic process using a second, and probably even-more-perennial, functional data example: the Canadian weather data in the fda
package. Here, functional data are stored in a three-dimensional array, with dimensions corresponding to day, station, and outcome (temperature, precipitation, and log10 precipitation).
In the following, we first create a tibble
with scalar covariates, then use tfd
to create functional data vectors, and finally include the resulting vectors in the dataframe. In this case, our arg
s are days of the year, and we use tf_smooth
to smooth the precipitation outcome. Because the original data matrices record the different observations in the columns instead of the rows, we have to use their transpose in the call to tfd
:
canada <- tibble( place = fda::CanadianWeather$place, region = fda::CanadianWeather$region, lat = fda::CanadianWeather$coordinates[, 1], lon = -fda::CanadianWeather$coordinates[, 2] ) |> mutate( temp = t(fda::CanadianWeather$dailyAv[, , 1]) |> tfd(arg = 1:365), precipl10 = t(fda::CanadianWeather$dailyAv[, , 3]) |> tfd(arg = 1:365) |> tf_smooth() )
The resulting data frame is shown below.
canada
A plot containing both functional observations is shown below.
temp_panel <- canada |> ggplot(aes(y = temp, color = region)) + geom_spaghetti() precip_panel <- canada |> ggplot(aes(y = precipl10, color = region)) + geom_spaghetti() gridExtra::grid.arrange(temp_panel, precip_panel, nrow = 1)
tf
from a data frame"Long" format data frames containing functional data include columns containing a subject identifier, the functional argument, and the value each subject's function takes at each argument. There are also often (but not always) non-functional covariates that are repeated within a subject. For data in this form, we use tf_nest
to produce a data frame containing a single row for each subject.
A first example is the pig weight data from the SemiPar
package, which is a nice example from longitudinal data analysis. This includes columns for id.num
, num.weeks
, and weight
-- which correspond to the subject, argument, and value.
data("pig.weights", package = "SemiPar") pig.weights <- as_tibble(pig.weights) pig.weights
We create pig_df
by nesting weight within subject. The result is a data frame containing a single row for each pig, and columns for id.num
and the weight
function.
pig_df <- pig.weights |> tf_nest(weight, .id = id.num, .arg = num.weeks) pig_df
We'll make a quick plot to show the result.
pig_df |> ggplot(aes(y = weight)) + geom_spaghetti()
A second example uses the ALA::fev1
dataset. ALA
is not available on CRAN but can be installed using the line below.
install.packages("ALA", repos = "http://R-Forge.R-project.org")
In this dataset, both height
and logFEV1
are observed at multiple ages for each child; that is, there are two functions observed simultaneously, over a shared argument. We can use tf_nest
to create a dataframe with a single row for each subject, which includes both non-functional covariates (like age and height at baseline), and functional observations logFEV1
and height
.
ALA::fev1 |> glimpse() ## Rows: 1,994 ## Columns: 6 ## $ id <fct> 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, … ## $ age <dbl> 9.3415, 10.3929, 11.4524, 12.4600, 13.4182, 15.4743, 16.3723, 6.5873, 7.6496, 12.7392, 13.7741, 14.6940, 15.… ## $ height <dbl> 1.20, 1.28, 1.33, 1.42, 1.48, 1.50, 1.52, 1.13, 1.19, 1.49, 1.53, 1.55, 1.56, 1.57, 1.57, 1.18, 1.23, 1.30, … ## $ age0 <dbl> 9.3415, 9.3415, 9.3415, 9.3415, 9.3415, 9.3415, 9.3415, 6.5873, 6.5873, 6.5873, 6.5873, 6.5873, 6.5873, 6.58… ## $ height0 <dbl> 1.20, 1.20, 1.20, 1.20, 1.20, 1.20, 1.20, 1.13, 1.13, 1.13, 1.13, 1.13, 1.13, 1.13, 1.13, 1.18, 1.18, 1.18, … ## $ logFEV1 <dbl> 0.21511, 0.37156, 0.48858, 0.75142, 0.83291, 0.89200, 0.87129, 0.30748, 0.35066, 0.75612, 0.86710, 1.04732, … ALA::fev1 |> group_by(id) |> mutate(n_obs = n()) |> filter(n_obs > 1) |> tf_nest(logFEV1, height, .arg = age) |> glimpse() ## Rows: 252 ## Columns: 6 ## $ id <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 3… ## $ age0 <dbl> 9.3415, 6.5873, 6.9131, 6.7598, 6.5024, 6.8994, 6.4339, 7.1869, 6.8966, 7.7892, 7.6140, 7.5483, 7.8412, 6.50… ## $ height0 <dbl> 1.20, 1.13, 1.18, 1.15, 1.11, 1.24, 1.18, 1.27, 1.17, 1.13, 1.32, 1.25, 1.25, 1.20, 1.19, 1.24, 1.21, 1.23, … ## $ n_obs <int> 7, 8, 9, 10, 7, 11, 7, 9, 9, 10, 6, 3, 5, 11, 12, 10, 9, 8, 12, 2, 2, 11, 11, 7, 9, 11, 11, 4, 2, 12, 3, 9, … ## $ logFEV1 <tfd_irrg> [<9.3415, 10.3929, 11.4524, 12.4600, 13.4182, 15.4743, 16.3723>, <0.21511, 0.37156, 0.48858, 0.75142, 0… ## $ height <tfd_irrg> [<9.3415, 10.3929, 11.4524, 12.4600, 13.4182, 15.4743, 16.3723>, <1.20, 1.28, 1.33, 1.42, 1.48, 1.50, 1…
In some cases functional data are stored in "wide" format, meaning that there are separate columns for each argument, and values are stored in these columns. In this case, tf_gather
can be use to collapse across columns to produce a function for each subject.
The example below again uses the refund::DTI
dataset. We use tf_gather
to transfer the cca
observations from a matrix column (with NA
s) into a column of irregularly observed functions (tfd_irreg
).
dti_df <- refund::DTI |> janitor::clean_names() |> select(-starts_with("rcst")) |> glimpse() dti_df |> tf_gather(starts_with("cca")) |> glimpse()
fda
and fd
coming soon ...
tidyfun
includes a wide range of tools for exploratory analysis and visualization, but many analysis approaches require data to be stored in more traditional formats. Several functions are available to aid in this conversion.
tf
to data framesThe functions tf_unnest
and tf_spread
reverse the operations in tf_nest
and tf_gather
, respectively -- that is, they take a data frame with a functional observation and produce long or wide data frames. We'll illustrate these with the pig_df
data set.
First, to produce a long-format data frame, one can use tf_unnest
:
pig_df |> tf_unnest(cols = weight) |> glimpse()
To produce a wide-format data frame, one can use tf_spread
:
pig_df |> tf_spread() |> glimpse()
To convert tf
vector to a matrix with each row containing the function evaluations for one function, use as.matrix
:
weight_vec <- pig_df$weight weight_matrix <- weight_vec |> as.matrix() head(weight_matrix) # argument values of input data saved in `arg`-attribute: attr(weight_matrix, "arg")
To convert a tf
vector to a standalone data frame with "id"
,"arg"
,"value"
-columns, use as.data.frame()
with unnest = TRUE
:
weight_vec weight_vec |> as.data.frame(unnest = TRUE) |> head()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.