R中的频率比

new*_*555 2 r histogram

我有两个文件中的数据。我想绘制一个图表,说明它们的频率之比。

例如,在我的文件中,从 1 到 5 的数字出现了 20 次。在我的文件 B 中,从 1 到 5 的数字出现了 10 次(直方图的条宽为 5)。这两者的比率是 20/10 = 2。我想在图表中绘制这个比率。可以用R来完成吗?

nic*_*ico 5

假设您阅读了变量中的 2 个文件data1data2您可以执行以下操作:

bins <- seq(0, 100, 5) # Change this to whatever range your data encopasses
h1 <- hist(data1, bins, plot=0)
h2 <- hist(data2, bins, plot=0)

ratio <- h1$counts/h2$counts
# Remove NaNs and Infs due to 0 counts
ratio[is.na(ratio)] <- 0
ratio[is.inf(ratio)] <- 0
barplot(ratio)
Run Code Online (Sandbox Code Playgroud)

或者,您可以创建第三个 hist 对象,其优点是可以正确绘制 x 轴

h3 <- h1
h3$counts <- ratio
plot(h3, col="black")
Run Code Online (Sandbox Code Playgroud)