首页 > 解决方案 > 如何迭代表列表并在R中查找比例

问题描述

我在 R 中有一个表列表,其中每个表都是来自更大数据集的列。这些是表格而不是数据框,因为我想使用 prop.table 来查找数据的出现百分比。

我是 R 新手,所以我一直在手动查找每个表的百分比。我试图把它变成一个 for 循环,但它似乎不起作用。该循环循环正确的次数,但每次打开一个新的 View() 表时,它都会给我最后一个表“Actually_Malicious”的结果。

categorical_variables_list = list(Download_Source, 
                                  TLD, 
                                  Download_Speed, 
                                  Executable_Code_Maybe_Present_in_Headers,
                                  No_Executable_Code_Found_In_Headers,
                                  Evidence_of_Code_Obfuscation,
                                  Actually_Malicious)


for(col in 1:length(categorical_variables_list)){
  
  tab <- table(categorical_variables_list[[col]]); 
  View(tab);
  prop <- prop.table(tab); 
  View(prop);
}

标签: rloopsfor-loop

解决方案


可能是这样的,如果你放一个数据样本,答案可能会更清晰,你可以在下面尝试,但你也可以选择lapply,我已经添加了我的列列表(这里使用了 mtcars 数据集):

categorical_variables_list<- list(mtcars[['cyl']], mtcars[['am']], mtcars[['vs']])

tab <- vector('list', length(categorical_variables_list)) 
prop <- vector('list', length(categorical_variables_list))

for(col in 1:length(categorical_variables_list)){
  
  tab[[col]] <- table(categorical_variables_list[[col]]);

  prop[[col]] <- prop.table(tab[[col]]) 

}

您的最终结果将在选项卡和道具中。使用 lapply 您可以执行以下操作:

tab <- lapply(categorical_variables_list,table)
prop <- lapply(tab, prop.table)

说明

在代码这里初始化tab/prop,你也可以做list(),但是它并没有告诉R list 的长度有多长,使用vector('list', length(...)) 都使用了为了方便以及高效地执行 for 循环,如果初始化正确,则 for 循环会以速度运行。vector 的参数如下,第一个参数是你要创建的数据类型,假设如果你想创建一个数字原子向量而不是列表,那么你可以写 vector('numeric', length(...) ) 等对于其他类型,这里我想要列表因此写为向量('list',长度(...)),第二个参数只是它应该运行的 for 循环的长度(多少次),因为我知道将运行您的列表的长度。它是这样提到的。我希望这可以消除所有疑问。lapply很容易,


推荐阅读