简体   繁体   English

将 df 转置为 R 中的每一行作为列

[英]Transpose a df with each row as a column in R

Using dplyr I would like to transpose the dataframe below.使用 dplyr 我想转置下面的 dataframe。

I used: t() but it didn't register my column names as a column.我使用: t() 但它没有将我的列名注册为列。 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

We can use pivot_longer()我们可以使用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

gather(df, sentiment, count)

Or using melt from data.table或使用data.tablemelt

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

Or with flatten and enframe或者使用flattenenframe

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

In base R , we can use stackbase R中,我们可以使用stack

stack(df)[2:1]

Base R solution (not as eloquent as akrun's stack solution):基础 R 解决方案(不像 eloquent 作为 akrun 的堆栈解决方案):

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:另一个 Tidyverse 解决方案:

library(tidyverse)
df %>% 
  t() %>% 
  data.frame() %>% 
  rename(., count = .) %>% 
  rownames_to_column("sentiment") %>% 
  arrange(count)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM