Hello, I am relatively new to R. I am trying to do the following and cannot figure out a relatively fast, clean method of doing it in R. Here is a simple sample of what my data set looks like: ID Try Num Dir 1 1 1 1 1 1 2 4 1 1 3 2 1 2 1 4 1 2 2 3 2 1 1 3 2 1 2 1 2 2 1 1 2 2 2 2 2 2 1 4 2 3 2 1 2 3 1 3 3 1 1 1 3 1 2 4 3 1 3 1 3 1 4 3 3 2 1 4 3 2 2 3 I would like to calculate the percent occurrence of each possible value of Dir (in this case, there are four: 1, 2, 3 and 4) for each ID and Num. E.g., so the output would be a table with each row as a different value of ID (in this case, 1, 2 and 3), and there would be a separate column for each instance of Dir for each instance of Num (in this case, for each of the 4 values of Num, there would be 4 columns for Dir). In this case, the first entry of this table would be .5, since for ID 1, when Num=1, Dir=1 in one out of two cases. Any help would be greatly appreciated! Thank you. [[alternative HTML version deleted]]
Henrique Dallazuanna
2010-Oct-28 12:45 UTC
[R] Calculate percent occurrence of different values
Try this: prop.table(xtabs(~ paste(ID, Num) + Dir, x), 1) On Thu, Oct 28, 2010 at 7:06 AM, Vanessa J <vanjan17@hotmail.com> wrote:> > Hello, > > I am relatively new to R. I am trying to do the following > and cannot figure out a relatively fast, clean method of doing it in R. > Here is a simple sample of what my data set looks like: > > ID Try Num Dir > 1 1 1 1 > 1 1 2 4 > 1 1 3 2 > 1 2 1 4 > > 1 2 2 3 > 2 1 1 3 > 2 1 2 1 > 2 2 1 1 > > 2 2 2 2 > 2 2 1 4 > > 2 3 2 1 > 2 3 1 3 > 3 1 1 1 > 3 1 2 4 > 3 1 3 1 > 3 1 4 3 > 3 2 1 4 > > 3 2 2 3 > > I would like to calculate the percent > occurrence of each possible value of Dir (in this case, there are four: > 1, 2, 3 and 4) for each ID and Num. E.g., so the output would be a table > with each row as a different value of ID (in this case, 1, 2 and 3), > and there would be a separate column for each instance of Dir for each > instance of Num (in this case, for each of the 4 values of Num, there > would be 4 columns for Dir). In this case, the first entry of this table > would be .5, since for ID 1, when Num=1, Dir=1 in one out of two cases. > Any help would be greatly appreciated! > > Thank you. > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]
Reasonably Related Threads
- Selecting the first occurrence of a value after an occurrence of a different value
- counting occurrence of text in a dataframe
- How to calculate values with percent sign imported from Excel?
- Percent of a given subset
- List of tables rather than an extra dimension in the table or (l)apply(xtabs)