[R] Transformations in Tidyverse (renaming and ordering columns)

Joel Maxuel j@m@xuel @ending from gm@il@com
Mon Oct 22 14:27:09 CEST 2018


Hello all,

I am slowly picking away at a factsheet that will include several result
sets from a single tibble (there is a column identifying the section title)
and would like to have that value in the top left corner of each resulting
table.  When using the `spread` function, I see that any remaining columns
not identified by `key` nor `value` will be placed to the far left.

Like the example below, I would like the column label Fiscal be renamed to
the data value "A", so the top-left of the result is "A".  However, if I
try to progmatically set the column name, I run into issues:


library(knitr)
library(tidyverse)
library(tibble)
library(dplyr)
library(magrittr)

testset <- as_tibble(tribble(~Section, ~Observation, ~Order, ~Fiscal,
~Value,
                             "A", "One", 1, "2016-17", 419,
                             "A", "One", 1, "2017-18", 499,
                             "A", "One", 1, "2018-19", 463,
                             "A", "Two", 2, "2016-17", 391,
                             "A", "Two", 2, "2017-18", 445,
                             "A", "Two", 2, "2018-19", 423,
                             "A", "Three", 3, "2016-17", 348,
                             "A", "Three", 3, "2017-18", 353,
                             "A", "Three", 3, "2018-19", 357))
sectionA <- as_tibble(filter(testset, Section == "A")) # Mind you for this
example, does very little
spread(select(sectionA, Observation, "A" = Fiscal, Value), key=Observation,
value=Value) # Works, with reservations
spread(select(sectionA, Observation, slice(sectionA,1) %>%
magrittr::extract2("Section") = Fiscal, Value), key=Observation,
value=Value) # Produces error:
# Error: unexpected '=' in "spread(select(sectionA, Observation,
slice(sectionA,1) %>% magrittr::extract2("Section") ="


I presume my premise is very wrong.

Also, I am curious how to sort columns (and rows) with extra columns
(/rows) not meant for display.  In this case, the columns One, Two, and
Three (in real life won't be linguistic representations of numbers), are
out of order - however I do have the Order column to fix that (if I knew
how to include it for sorting purposes, without displaying it).  A few
hints here would help.  (Perhaps there is column/row hiding in kableExtra -
which I will be using later on?)

--
Cheers,
Joel Maxuel

	[[alternative HTML version deleted]]



More information about the R-help mailing list