R计算数据框中的百分比值 [英] R compute percentage values in data frame

查看:230
本文介绍了R计算数据框中的百分比值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天的问题是指我正在R中处理的数据框. 数据帧的标题如下:String(unique),Integer N [0-23]

My question today refers to a data frame I'm working on in R. The header of the data frame looks like the following: String(unique), Integer N[0-23]

这24个Integer值表示与一天中的每个小时关联的String的频率.从逻辑上讲,每一行的int值总和该字符串在数据中出现的频率.

Those 24 Integer values represent the frequency of the String associated with each hour of the day. Logically, the int values in each row sum up to the number how often the string appears in the data in general.

问题是,我不需要某个小时的字符串的实际频率,而是该频率相对于所有行中整数值之和的百分比.

Thing is, I don't need the real frequency of the string at a certain hour but the percentage this frequency represents in relation to the sum of the integer values in all rows.

我的讲师暗示table()可能是正确的R工具,但老实说,我不明白这对我有什么帮助.

My lecturer hinted that table() might be the right R tool for that but I honestly don't understand how that is supposed to help me.

如果所有其他方法都失败了,我将用Java进行计算-尽管我非常感谢您在R中进行此操作的帮助.

If all else fails, I'll calculate it in Java - although I'd really appreciate your help to do this in R.

感谢您的阅读,并在此先感谢您的帮助,

Thanks for reading so far and thanks in advance for your help,

Rickyfox

@@@@@@@我是你的编辑,请给我读@@@@@@@

@@@@@@I am your edit, read me @@@@@@

在我从詹姆斯那里得到的帮助下,我得到了以下合适的

With the help I got from James I got the following proptable

事实是,每一行的百分比总计为100,但是对于整个表,它们应该这样做.有办法吗?

Thing is, the percentages sum up to 100 for each row, but they should do so for the whole table. Is there a way to do that?

推荐答案

在包含值的matrix上使用prop.table:

x <- data.frame(id=letters[1:3],val0=1:3,val1=4:6,val2=7:9)
prop.table(as.matrix(x[-1]),margin=1)
           val0      val1      val2
[1,] 0.08333333 0.3333333 0.5833333
[2,] 0.13333333 0.3333333 0.5333333
[3,] 0.16666667 0.3333333 0.5000000

一个完整的示例:

tt=read.table("topichitsperhod.csv",sep=",",header=TRUE)  
tt=na.omit(tt[-1])
pt=prop.table(tt[-1],margin=NULL)

由于保留了主题字符串,因此第一列被排除在外.

First column is being left out because it held the topic strings.

这篇关于R计算数据框中的百分比值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆