Data Frame Manipulation


#1

Hi, i have the following data frame

# A tibble: 3 x 4
  month net_sales visitor clicks
  <chr>  <dbl>    <dbl>  <dbl>
1 Jan     32.0     3.00  12.0 
2 Feb     43.0     2.00  11.0 
3 Mrz     21.0     6.00   8.00

and want to achieve the following:

Colname     Jan     Feb     Mrz
net_sales   32.0  42.00    21.0
visitors    3.00   2.00    6.00
clicks     12.00  11.00    8.00

How would u approache that?

Thanks in advance :slight_smile:


#2

You should be able to accomplish this using the spread() function.

https://tidyr.tidyverse.org/reference/spread.html


#3

Use the t() function to transpose matrices or data frames.

my_new_data <- t(my_data[, -1])
my_new_data[["Colname"]] <- names(my_data)[-1]

#4

You need to reshape your dataframe and the tidyverse tool for that is tidyr. It is included when you call library(tidyverse)

To change the shape you need first to tidy your data (column = variable, row = observation, cell = value) with gather and then spread to change the shape. Note that you should keep your data in tidy format (after gather) to do further manipulation before reshaping with spread

library(tidyverse)
df <- tribble(
  ~month, ~net_sales, ~visitor, ~clicks,
   "Jan",         32,        3,      12,
   "Feb",         43,        2,      11,
   "Mrz",         21,        6,       8
  )
df %>%
  gather('Colname', 'value', -month) %>%
  # You can use ordered factor to keep sorted
  mutate(month = fct_inorder(month)) %>%
  spread(month, value)
#> Warning: le package 'bindrcpp' a été compilé avec la version R 3.4.4
#> # A tibble: 3 x 4
#>   Colname     Jan   Feb   Mrz
#>   <chr>     <dbl> <dbl> <dbl>
#> 1 clicks       12    11     8
#> 2 net_sales    32    43    21
#> 3 visitor       3     2     6

Created on 2018-07-04 by the reprex package (v0.2.0).


#5

I was thinking about using either the spread() or the gather() function but not both especially because i considered them as complement functions. But this makes absolutely sense.

Thank you very much!


#6

If your question's been answered, would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it: