Dear RStudio Community,
How can I turn a dataframe, where each row of data is a unique observation, and turn it into a series of long tables where each table is an observation with two variables - the variable name and the value of the variable?
library(tibble)
library(tidyr)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
# this is how my data looks, except I have many more variables
my_data <- tibble(
id = c("001", "002", "003", "004"),
color = c("red", "yellow", "blue", "violet"),
fruit = c("apple", "banana", "blueberry", "plum"),
animal = c("dog", "cat", "bird", "fish"),
description = c("adorable", "curious", "bewildered", "dull")
)
# i want to display my data, in an rmarkdown document, as a series of long tables like this
my_target_data_id_001 <- tibble(
"variable" = c(
"color",
"fruit",
"animal",
"description"
),
"001" = c(
"red",
"apple",
"dog",
"adorable"
)
)
my_target_data_id_002 <- tibble(
"variable" = c(
"color",
"fruit",
"animal",
"description"
),
"002" = c(
"yellow",
"banana",
"cat",
"curious"
)
)
my_target_data_id_003 <- tibble(
"variable" = c(
"color",
"fruit",
"animal",
"description"
),
"003" = c(
"blue",
"blueberry",
"bird",
"bewildered"
)
)
# and so on
Created on 2022-04-12 by the reprex package (v2.0.1)
Session info
sessionInfo()
#> R version 4.1.3 (2022-03-10)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 19044)
#>
#> Matrix products: default
#>
#> locale:
#> [1] LC_COLLATE=English_United States.1252
#> [2] LC_CTYPE=English_United States.1252
#> [3] LC_MONETARY=English_United States.1252
#> [4] LC_NUMERIC=C
#> [5] LC_TIME=English_United States.1252
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] dplyr_1.0.8 tidyr_1.2.0 tibble_3.1.6
#>
#> loaded via a namespace (and not attached):
#> [1] pillar_1.7.0 compiler_4.1.3 highr_0.9 R.methodsS3_1.8.1
#> [5] R.utils_2.11.0 tools_4.1.3 digest_0.6.29 evaluate_0.15
#> [9] lifecycle_1.0.1 R.cache_0.15.0 pkgconfig_2.0.3 rlang_1.0.2
#> [13] reprex_2.0.1 DBI_1.1.2 cli_3.2.0 rstudioapi_0.13
#> [17] yaml_2.3.5 xfun_0.30 fastmap_1.1.0 withr_2.5.0
#> [21] styler_1.7.0 stringr_1.4.0 knitr_1.38 generics_0.1.2
#> [25] fs_1.5.2 vctrs_0.3.8 tidyselect_1.1.2 glue_1.6.2
#> [29] R6_2.5.1 fansi_1.0.3 rmarkdown_2.13 purrr_0.3.4
#> [33] magrittr_2.0.2 ellipsis_0.3.2 htmltools_0.5.2 assertthat_0.2.1
#> [37] utf8_1.2.2 stringi_1.7.6 crayon_1.5.1 R.oo_1.24.0