每个因子水平组合的“加权”计数

时间:2020-03-21 11:36:27

标签: r dataframe data-manipulation

我有以下

> df=data.frame(from = c("x","y","x","z"), to=c("w","x","w","y"),weight=c(1,1,3,4))
> df
  from to weight
1    x  w      1
2    y  x      1
3    x  w      3
4    z  y      4

如果我想计算列from的元素在中出现多少次,我需要使用:

> table(df$from)
x y z 
2 1 1 

这不是加权和。无论如何,我怎么也考虑列weight?例如。在我的示例中,正确答案应该是:

x y z 
4 1 4 

2 个答案:

答案 0 :(得分:1)

您可以使用package main; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import javax.swing.UIManager; public class Main { public Main() { } public static void main(String args[]) { ArrayList<String> uiKeys = new ArrayList<>(); String fileName = "recources/UIManagerKeys.txt"; ClassLoader classLoader = new Main().getClass().getClassLoader(); File file = new File(classLoader.getResource(fileName).getFile()); // Check: is File found? System.out.println("File Found : " + file.exists()); try { // Read File Content String content = new String(Files.readAllBytes(file.toPath())); // Split by line and collect String[] keys = content.split("\n"); uiKeys.addAll(Arrays.asList(keys)); } catch (IOException e) { System.out.println("Error: " + e); } // Output / Test - stream Keys System.out.println("Total Number of Keys: " + uiKeys.size()); String suffix = ""; // Interesting behavior when String is not empty uiKeys.stream() .map(key -> key.replaceAll(" ", "").replaceAll("\n", "")) // Just to be sure .forEach(key -> System.out.println("IconFound: " + (UIManager.getIcon(key) != null) + "\tKey: " + key + suffix)); // Output / Test - single Key System.out.println("\n"); String key = "FileView.directoryIcon"; // Copied from console System.out.println("IconFound: " + (UIManager.getIcon(key) != null) + "\tKey: " + key + suffix); } } 并为tapply的每个唯一值计算sum

from

答案 1 :(得分:1)

我们可以使用count中的dplyr

library(dplyr)
df %>% 
    count(from, wt = weight)
#  from n
#1    x 4
#2    y 1
#3    z 4

base R中,我们可以使用xtabs

xtabs(weight~ from, df)
#from
#x y z 
#4 1 4