Reputation: 329
probably someone has an advice.
I m working on a report with knitR and the tables package. The function tabular generates my Latex code.
I want a table with absolute and relative frequencies, but I dont know how to get it.
I tried to apply within tabular an own function that generates the relative values:
relative <- function(x){
len <- length(x)
ll <- length(table(x))
lev <- unique(x)
out <- numeric(length = ll)
for(i in 1:ll){
pos <- which(x == lev[i])
out[i] <- length(pos)/len*100
}
return(out)
}
The function I put in the tabular function with Country and Type as two factors.
tabular(Country ~ Type*relative, data = cars)
Here the result:
Type
PKW SUV
Country relative relative
Germany 0 0
Japan 0 0
Other 0 NaN
USA 0 0
The result is just the example of how it doesnt work :) My main target is a table that contains both: absolute AND relative frequencies with tabular.
To clearify the problem: Here the result without the function relative:
tabular(Country ~ Type, data = cars)
Type
Country PKW SUV
Germany 23 1
Japan 22 17
Other 12 0
USA 58 22
Does anyone has an idea how to get the table?
Thanks in advance!
Upvotes: 1
Views: 864
Reputation: 329
From the vignette:
The last factor, (mean + sd) names two R functions. These are assumed to be functions that operate on a vector and produce a single value, as mean and sd do. The values in the table will be the results of applying those functions to the two dierent variables and the subsets of the dataset.
I have overlooked this part that is the crucial hint, why the function i wrote doesnt work. "relative" returns a vector as long as manifestations the variable x has - allowed is an atomic vector. The problem is now that there is no way to add the basis into the function to calculate the relative values - the returning value is calculated from an subset of x.
Actually this is working but is not the most elegant way. I wrote the function with a hard coded nrow (here: 155).
relative <- function(x){
round(length(x)/155, 2)
}
tabular(Country ~ Type + relative, data = cars)
Type
Country PKW SUV relative
Germany 23 1 0.15
Japan 22 17 0.25
Other 12 0 0.08
USA 58 22 0.52
If anyone find a better solution - please help :)
Upvotes: 2