1

Using dplyr I would like to transpose the dataframe below.

I used : t() but it didn't register my column names as a column. Additionally, I want to name the columns

df <- structure(list(anger = 4083, anticipation = 7023, disgust = 2551, 
    fear = 6983, joy = 4316, negative = 9234, positive = 17198, 
    sadness = 3690, surprise = 2996, trust = 11146), row.names = c(NA, 
-1L), class = c("tbl_df", "tbl", "data.frame"))

Preferably this should be arranged by count.

**sentiment        count**
anger             4083
anticipation      7023
disgust           2551
fear              6983
joy               4316
negative          9234
positive         17198
sadness           3690
surprise          2996
trust            11146
Johnny Thomas
  • 623
  • 5
  • 13
  • 2
    Does this answer your question? [Reshaping data.frame from wide to long format](https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format) – camille Apr 17 '20 at 04:25

2 Answers2

1

We can use pivot_longer()

library(dplyr)
library(tidyr)
df %>% 
   pivot_longer(everything(), names_to = 'sentiment', values_to = 'count') %>% 
   arrange(count)
# A tibble: 10 x 2
#   sentiment    count
#   <chr>        <dbl>
# 1 disgust       2551
# 2 surprise      2996
# 3 sadness       3690
# 4 anger         4083
# 5 joy           4316
# 6 fear          6983
# 7 anticipation  7023
# 8 negative      9234
# 9 trust        11146
#10 positive     17198

Or with gather

gather(df, sentiment, count)

Or using melt from data.table

library(data.table)
melt(setDT(df), variable.name = 'sentiment', measure.vars = names(df),
           value.name = 'count')[order(count)]

Or with flatten and enframe

library(tibble)
library(purrr)
flatten(df) %>% 
      enframe %>%
      unnest(c(value))

In base R, we can use stack

stack(df)[2:1]
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Base R solution (not as eloquent as akrun's stack solution):

rpd_df <- data.frame(sentiment = names(df),
                     count = t(df),
                     row.names = NULL)

ord_rpd_df <- rpd_df[with(rpd_df, order(count)),]

Another Tidyverse solution:

library(tidyverse)
df %>% 
  t() %>% 
  data.frame() %>% 
  rename(., count = .) %>% 
  rownames_to_column("sentiment") %>% 
  arrange(count)
hello_friend
  • 5,682
  • 1
  • 11
  • 15