我有一個資料集,其中包含對 26 個問題的數百個參與者和控制回應。每個參與者都有 26 個與他們相關的問題,他們回答是 (1)、否 (-1)、可能 (0) 或沒有回答 (NA)
對于每個參與者,我想總結他們對所有 26 個問題的所有具體回答,并將其保存到一個新列中。因此,如果他們在 26 次中回答是 (1) 12 次,那么新列中應該包含數字 12——忽略否 (-1) 值。
我嘗試過 for 回圈、if else 陳述句、子設定、group by 和 sum 等。我只是不知道如何遍歷 26 個問題中的每一個并僅對他們的問題求和——忽略其他參與者。
編輯:這是代碼外觀的代表性示例。
ID PatientResponse ControlResponse QuestionNumber
1 122047 1 0 1
2 123274 -1 -1 1
3 186223 1 1 1
4 122047 0 -1 2
5 123274 1 -1 2
6 186223 -1 0 2
這是一個問題對于不同參與者的樣子的影像:https : //i.stack.imgur.com/ojGGO.png
在為每個參與者總結了所有 26 個問題之后,我希望它的理想情況如下:https : //i.stack.imgur.com/W6Qo3.png
uj5u.com熱心網友回復:
library(dplyr); library(tidyr)
# this will give the count of each kind of response in its own column
df %>%
count(Question, Participant, Control) %>%
pivot_wider(names_from = Control, values_from = n)
#if you just want Yes's counted
df %>%
group_by(Question, Participant) %>%
summarize(Summed_Yes_Responses = sum(Control == 1, na.rm = TRUE))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318524.html
