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

Joel Maxuel j@m@xue| @end|ng |rom gm@||@com
Tue Oct 23 12:12:11 CEST 2018


I am impressed.  Upon playing with factor, I took it a step further to
commonize (and this could very well be simpified):

>
> testset$Observation <- factor(testset$Order, levels=testset$Order,
labels=testset$Observation)
> testset$Label <- factor(testset$Seq, levels=testset$Seq,
labels=testset$Label)
>
>     testset %>% select(Observation, Label, Value) %>%
spread(key=Observation, value=Value)
# A tibble: 4 x 4
  Label      One   Two Three
  <fct>    <dbl> <dbl> <dbl>
1 Western    163   147   119
2 Northern   105   100    82
3 Eastern    121   106    90
4 Southern    74    70    65
>

All I see left now is to replace "Label" heading value with the appropriate
testset$Section value provided for the situation.  In this case...

# A tibble: 4 x 4
  For Reporting Quarter      One   Two Three
  <fct>                               <dbl> <dbl> <dbl>
...

FWIW, before sending this I cleared all formatting and dismissed the
formatting toolbar (been doing only the latter before) in the Gmail client,
which I presume will finally strip HTML from the message.

--
Cheers,
Joel Maxuel

On Mon, Oct 22, 2018 at 10:48 PM John Laing <john.laing using gmail.com> wrote:

> I don't know much about the Tidyverse, but more generally the way to
> represent ordered categorical data is with a factor. This seems to work:
>
> > testset$Observation <- factor(testset$Observation, levels=c("One",
> "Two", "Three"))
> > testset$Label <- factor(testset$Label, levels=c("Western", "Northern",
> "Eastern", "Southern"))
> > testset %>% select(Observation, Label, Value) %>%
> spread(key=Observation, value=Value)
> # A tibble: 4 x 4
>   Label      One   Two Three
>   <fct>    <dbl> <dbl> <dbl>
> 1 Western    163   147   119
> 2 Northern   105   100    82
> 3 Eastern    121   106    90
> 4 Southern    74    70    65
>
>>
>>

	[[alternative HTML version deleted]]




More information about the R-help mailing list