[英]Count of values across multiple columns in R
我有一個數據集,其中一組值分散在多列中:
優先級 1 | 優先級 2 | 優先級 3 |
---|---|---|
寫作 | 讀 | 讀 |
讀 | 溝通 | 寫作 |
溝通 | 寫作 | 溝通 |
寫作 | 溝通 | 寫作 |
我希望輸出是一個表格,其中第一列是找到的唯一值(寫作、閱讀、交流),其余列是優先級(優先級 1、優先級 2、優先級 3)。 在每一列中應該是該實例的優先級計數。 輸出應如下所示:
優先類型 | 優先級 1 | 優先級 2 | 優先級 3 |
---|---|---|---|
寫作 | 2 | 1 | 2 |
讀 | 1 | 1 | 1 |
溝通 | 1 | 2 | 1 |
在我的實際數據集中,有很多優先級,所以如果可能的話,我們可以為列包含 1:n 嗎?
先感謝您。
table(stack(df))
ind
values Priority 1 Priority 2 Priority 3
Communication 1 2 1
Reading 1 1 1
Writing 2 1 2
如果你想把它作為數據框:
as.data.frame.matrix(table(stack(df)))
Priority 1 Priority 2 Priority 3
Communication 1 2 1
Reading 1 1 1
Writing 2 1 2
試試sapply
sapply( dat, table )
Priority1 Priority2 Priority3
Communication 1 2 1
Reading 1 1 1
Writing 2 1 2
這是使用tidyr
包的pivot_wider
函數中的tidyr
values_fn = max
參數的tidyverse
解決方案:
library(dplyr)
library(tidyr)
df %>%
pivot_longer(
cols= everything()
) %>%
group_by(name) %>%
add_count(value) %>%
pivot_wider(
names_from = name,
values_from =n,
values_fn = max
)
value Priority1 Priority2 Priority3
<chr> <int> <int> <int>
1 Writing 2 1 2
2 Reading 1 1 1
3 Communication 1 2 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.