data_to_wide {datawizard} | R Documentation |
Reshape (pivot) data from long to wide
Description
This function "widens" data, increasing the number of columns and decreasing
the number of rows. This is a dependency-free base-R equivalent of
tidyr::pivot_wider()
.
Usage
data_to_wide(
data,
id_cols = NULL,
values_from = "Value",
names_from = "Name",
names_sep = "_",
names_prefix = "",
names_glue = NULL,
values_fill = NULL,
verbose = TRUE,
...
)
reshape_wider(
data,
id_cols = NULL,
values_from = "Value",
names_from = "Name",
names_sep = "_",
names_prefix = "",
names_glue = NULL,
values_fill = NULL,
verbose = TRUE,
...
)
Arguments
data |
A data frame to pivot. |
id_cols |
The name of the column that identifies the rows. If |
values_from |
The name of the column that contains the values to be used as future variable values. |
names_from |
The name of the column that contains the levels to be used as future column names. |
names_sep |
If |
names_prefix |
String added to the start of every variable name. This is
particularly useful if |
names_glue |
Instead of |
values_fill |
Optionally, a (scalar) value that will be used to replace missing values in the new columns created. |
verbose |
Toggle warnings. |
... |
Not used for now. |
Value
If a tibble was provided as input, reshape_wider()
also returns a
tibble. Otherwise, it returns a data frame.
See Also
Functions to rename stuff:
data_rename()
,data_rename_rows()
,data_addprefix()
,data_addsuffix()
Functions to reorder or remove columns:
data_reorder()
,data_relocate()
,data_remove()
Functions to reshape, pivot or rotate data frames:
data_to_long()
,data_to_wide()
,data_rotate()
Functions to recode data:
rescale()
,reverse()
,categorize()
,recode_values()
,slide()
Functions to standardize, normalize, rank-transform:
center()
,standardize()
,normalize()
,ranktransform()
,winsorize()
Split and merge data frames:
data_partition()
,data_merge()
Functions to find or select columns:
data_select()
,data_find()
Functions to filter rows:
data_match()
,data_filter()
Examples
data_long <- read.table(header = TRUE, text = "
subject sex condition measurement
1 M control 7.9
1 M cond1 12.3
1 M cond2 10.7
2 F control 6.3
2 F cond1 10.6
2 F cond2 11.1
3 F control 9.5
3 F cond1 13.1
3 F cond2 13.8
4 M control 11.5
4 M cond1 13.4
4 M cond2 12.9")
data_to_wide(
data_long,
id_cols = "subject",
names_from = "condition",
values_from = "measurement"
)
data_to_wide(
data_long,
id_cols = "subject",
names_from = "condition",
values_from = "measurement",
names_prefix = "Var.",
names_sep = "."
)
production <- expand.grid(
product = c("A", "B"),
country = c("AI", "EI"),
year = 2000:2014
)
production <- data_filter(production, (product == "A" & country == "AI") | product == "B")
production$production <- rnorm(nrow(production))
data_to_wide(
production,
names_from = c("product", "country"),
values_from = "production",
names_glue = "prod_{product}_{country}"
)