簡體   English   中英

將數據表列轉換為行以在 R 中創建可展示的表

[英]Convert Data Table Columns to Rows to Create Presentable Tables in R

嗨,當我繼續嘗試學習 R 時,我無法理解如何整理我的數據。 所以最后我很想有一張像這樣的桌子。 (省略平均值和改進列)

在此處輸入圖像描述

這是我目前擁有的數據表:

  group = c("Group 1", "Group 2", "Group 3", "Group 4", "Group 5",
                    "Group 6", "Group 7", "Group 8", "Group 9"),
  yes = c("9", "9", "9", "12", "12", "12", "10", "10", "10"),
  no = c("9", "9", "9", "6", "6", "6", "8", "8", "8"), 
  perc = c(0.5, 0.5, 0.5, 0.67, 0.67, 0.67, 0.56, 0.56, 0.56))

dt

 group yes no perc
1: Group 1   9  9 0.50
2: Group 2   9  9 0.50
3: Group 3   9  9 0.50
4: Group 4  12  6 0.67
5: Group 5  12  6 0.67
6: Group 6  12  6 0.67
7: Group 7  10  8 0.56
8: Group 8  10  8 0.56
9: Group 9  10  8 0.56

但是,我希望它重新格式化,我可以讓“是”和“否”列成為“響應”列名和 perc 列下的行,這表示說“是”的人的百分比也成為“響應”行之后的最后一行

Response Group 1 Group 2 Group 3 Group 4 Group 5...
yes      9       9       9       12      12 
no       9       9       9       6       6 
per      0.50    0.50    0.50    0.67    0.67

對此的任何幫助將不勝感激! 謝謝!

您正在使用data.table因此您可以這樣做:

transpose(dt,keep.names = 'Response',make.names = 'group')

   Response Group 1 Group 2 Group 3 Group 4 Group 5 Group 6 Group 7 Group 8 Group 9
1:      yes       9       9       9      12      12      12      10      10      10
2:       no       9       9       9       6       6       6       8       8       8
3:     perc     0.5     0.5     0.5    0.67    0.67    0.67    0.56    0.56    0.56

Note that if you have other libraries loaded eg purrr ensure to load transpose from the data.table package using the scope resolution operator ie data.table::transpose(...)

這是 tidyverse 解決方案:

library(dplyr)
library(tidyr)

dt %>% 
  pivot_longer(c(yes, no, perc),
               names_to = "key",
               values_to = "val", 
               values_transform = list(val = as.character)
               ) %>% 
  pivot_wider(names_from = group, values_from = val) %>% 
  mutate(across(-key, as.numeric))
 key   `Group 1` `Group 2` `Group 3` `Group 4` `Group 5` `Group 6` `Group 7` `Group 8` `Group 9`
  <chr>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>
1 yes         9         9         9       12        12        12        10        10        10   
2 no          9         9         9        6         6         6         8         8         8   
3 perc        0.5       0.5       0.5      0.67      0.67      0.67      0.56      0.56      0.56

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM