-1

After much frustration, I have written my own function to transpose Tibbles I've attempted to make it universal so I don't have to rewrite it in the future

Its purpose is a simple transpose like is possible in Excel special paste or t() for data frames its made for making tables that ill put in my publications that won't always follow the tidy principles

Would anyone be able to advice if there is any better way to write my function and also whats the best way for me to store this so I can access it quickly in the future? is it time for me to make my own package?

transpose_tibble<-function(tibble){
tibble%>%
  rename(rowname=1)%>%
  mutate(across(everything(),~as.character(.)))%>%
  pivot_longer(cols = !rowname ,names_to = 'variable',  values_to = 'value') %>%
  pivot_wider(id_cols = variable, names_from = rowname, values_from = value)%>%
  type.convert(as.is=TRUE)
}
  • 3
    Why not `t(as.data.frame(tibble))`? Whatever you choose, having a package to hold it is a very good idea. The `usethis::create_package` function makes it very easy to create one. Don't bother sending it to CRAN, just keep it for yourself. – user2554330 Jul 11 '23 at 11:54

1 Answers1

1

I think your function would do, but as you asked for improvements I would use this, it simplified your code a bit and it adds a small functionality to name the first column name. It defaults to your hardcoded "variable". As you already suggested if you plan to develop more custom generic functions, starting your own package is a good idea.

transpose_tibble <- function(x, variable_name = "variable") {
  x %>% 
    pivot_longer(cols = -1, names_to = variable_name, values_transform = as.character) %>%
    pivot_wider(names_from = 1, values_from = "value") %>%
    type.convert(as.is = TRUE)
}

df

# A tibble: 5 × 5
  group January February March April
  <chr>   <int>    <int> <int> <int>
1 A           1        2     3     4
2 B           2        3     4     5
3 C           3        4     5     6
4 D           4        5     6     7
5 E           5        6     7     8

transpose_tibble(df, "month")

# A tibble: 4 × 6
  month        A     B     C     D     E
  <chr>    <int> <int> <int> <int> <int>
1 January      1     2     3     4     5
2 February     2     3     4     5     6
3 March        3     4     5     6     7
4 April        4     5     6     7     8

Example data used

df <- tibble(group = LETTERS[1:5], January = 1:5, February = 2:6, March = 3:7, April = 4:8)
Merijn van Tilborg
  • 5,452
  • 1
  • 7
  • 22