View source: R/pivot-demand-data.R
| pivot_demand_data | R Documentation |
Converts demand data between wide format (one row per subject,
prices as columns) and long format (one row per observation with id, x,
y columns). This is a convenience wrapper around tidyr::pivot_longer()
and tidyr::pivot_wider() tailored for behavioral economic purchase task
data.
pivot_demand_data(
data,
format = c("long", "wide"),
id_var = "id",
x_var = "x",
y_var = "y",
price_cols = NULL,
x_values = NULL,
drop_na = TRUE
)
data |
A data frame or tibble to reshape. |
format |
Character. Direction of reshaping: |
id_var |
Character. Name of the subject/series identifier column.
Default |
x_var |
Character. Name of the price column in long-format data. Used
when |
y_var |
Character. Name of the consumption column in long-format data.
Used when |
price_cols |
Character vector of column names in wide-format data that
represent prices. Used when |
x_values |
Numeric vector of actual price values corresponding to each
price column in wide-format data. Used when |
drop_na |
Logical. When |
format = "long")The function determines which columns are price columns by:
If price_cols is provided, those columns are used directly.
If price_cols is NULL, column names are tested with as.numeric().
Columns whose names successfully parse as numbers (e.g., "0", "0.5",
"10") are treated as price columns. Remaining non-id_var columns are
preserved as extra identifiers.
If no column names parse as numeric, all non-id_var columns become price
columns and x_values must be supplied.
Actual numeric price values come from x_values if supplied, or from parsing
column names. If column names cannot be parsed and x_values is not supplied,
an error is raised.
format = "wide")Pivots long data so that each unique value in x_var becomes a column, with
values from y_var. All columns except x_var and y_var are used as
identifiers.
A tibble. When format = "long": columns id, any extra identifier
columns, x (numeric price), and y (numeric consumption). When
format = "wide": one row per subject with prices as column names.
# --- Wide to long ---
# Columns named as prices (auto-parsed)
wide_num <- data.frame(
id = 1:3,
"0" = c(10, 8, 12), "0.5" = c(9, 7, 11), "1" = c(8, 6, 9),
check.names = FALSE
)
pivot_demand_data(wide_num, format = "long")
# Columns with non-numeric names require x_values
wide_named <- data.frame(id = 1:2, price_1 = c(10, 8), price_2 = c(5, 4))
pivot_demand_data(wide_named, format = "long",
x_values = c(0, 0.5))
# --- Long to wide ---
data(apt, package = "beezdemand")
wide_apt <- pivot_demand_data(apt, format = "wide")
head(wide_apt)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.