我有一個資料集,其中一組值分散在多列中:
| 優先級 1 | 優先級 2 | 優先級 3 |
|---|---|---|
| 寫作 | 讀 | 讀 |
| 讀 | 溝通 | 寫作 |
| 溝通 | 寫作 | 溝通 |
| 寫作 | 溝通 | 寫作 |
我希望輸出是一個表格,其中第一列是找到的唯一值(寫作、閱讀、交流),其余列是優先級(優先級 1、優先級 2、優先級 3)。在每一列中應該是該實體的優先級計數。輸出應如下所示:
| 優先型別 | 優先級 1 | 優先級 2 | 優先級 3 |
|---|---|---|---|
| 寫作 | 2 | 1 | 2 |
| 讀 | 1 | 1 | 1 |
| 溝通 | 1 | 2 | 1 |
在我的實際資料集中,有很多優先級,所以如果可能的話,我們可以為列包含 1:n 嗎?
先感謝您。
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
嘗試 sapply
sapply( dat, table )
Priority1 Priority2 Priority3
Communication 1 2 1
Reading 1 1 1
Writing 2 1 2
uj5u.com熱心網友回復:
這是tidyverse使用包函式中的values_fn = max引數的解決方案:pivot_widertidyr
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/358112.html
上一篇:按學期和年份對串列檔案進行排序
