在缺少因子的位置添加一个级别

Add in a level of a factor where it is missing

提问人:Paul 提问时间:9/7/2022 更新时间:9/7/2022 访问量:59

问:

我有目前看起来像这样的数据:

子 ID 试用类型 频率
100 木塑 10
100 OP中。 20
100 BPT公司 15
100 太平绅士) 16
101 木塑 9
101 OP中。 7
101 太平绅士) 10

例如,在上表中,subID 是主题 ID 号,Trialtype 是 4 个级别(WPC、BPC、BPT 和 WPT)的分类,Freq 是试用类型的频率。在数据输入过程中,如果受试者的试验类型为 0,则该类别将被遗漏。参考该表,sub 101 完全缺少类别 BPC 的一行,因为它们的 BPC 试验计数为 0。这导致我正在运行的一些分析出现一些问题,我现在需要一个数据帧版本,其中行存在频率为 0 的行,而不是缺少行,如下所示:

子 ID 试用类型 频率
100 木塑 10
100 OP中。 20
100 BPT公司 15
100 太平绅士) 16
101 木塑 9
101 OP中。 7
101 BPT公司 0
101 太平绅士) 10

我正在尝试一个for循环来实现这一点,但我坚持如何将这些行添加到数据帧中。到目前为止,我有:

for (myperson in unique(data$subID)){

  #Create a list of all trial types
  trials=c("WPC", "BPC", "BPT", "WPT")
  
  #Does this person have all trial types?
  person_trial_list=unique(data$Trialtype[data$subID==myperson])
  
  trials=person_trial_list 

  #How to act on this information?
  
}

我已经看到了很多关于降低因子水平/行的威胁,但没有一个以我能够很好地理解的方式添加它们来实现。有人有解决方案吗?我对可能也有效的 tidyverse/dplyr 选项持开放态度。

R for 循环 数据操作

评论

1赞 akrun 9/7/2022
使用即completelibrary(tidyr);complete(data, subID, Trialtype, fill = list(Freq = 0))

答:

0赞 Paul 9/7/2022 #1

用户 akrun 在评论中建议,这效果很好:

library(tidyr)

complete(data, subID, Trialtype, fill = list(Freq = 0))