我有以下dataframe:
> 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
的元素在dataframe中出现多少次,我需要使用:
> table(df$from)
x y z
2 1 1
这不是加权和。无论如何,我怎么也考虑列weight
?例如。在我的示例中,正确答案应该是:
x y z
4 1 4
答案 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