Can R Produce Frequency Tables for One Variable?
Disclaimer: I Am New to Stackoverflow and R: I Have a Data Set Call "House" with Multiple Columns. I Am Trying to Obtain Different Frequency Tables for Each...
Disclaimer: I am new to Stackoverflow and R:
I have a data set call "house" with multiple columns. I am trying to obtain different frequency tables for each columns, without having them interact with each other. For this example: I am trying to obtain the overall count of houses that have pools and those that don't have pools. Sort of like a proc freq in SAS, where you do:
proc freq data = house;
tables pool backyard park_near / missing list;
run;
But don't have any of the variables interacting with each other.
I use the following code in R:
freq_2<- freqlist(table(house[("Pool")], useNA = "ifany"))
print.noquote(head(as.data.frame(freq_2), n=100L))
However, I get:
Var1 Freq cumFreq freqPercent cumPercent
1 N 64 64 88.88889 88.88889
2 Y 8 72 11.11111 100.00000
Is there anyway I can get "Pool" instead of "Var1"? Also is there an easier way of doing this in R?
Thank you in advance for the help.
2 Answers
Base R with arsenal::freqlist()
The code from the question uses arsenal::freqlist() to replicate the output from SAS PROC FREQ. Unfortunately, when printing freqlist() results as a data frame, the first column always renders as Var1, regardless of the actual variable whose frequencies are being printed.
A very simple fix is to rename the column before printing via the colnames() function. We can combine this with lapply() to create frequency tables for multiple columns from a data frame.
Here is an example that combines lapply() with colnames() to rename the Var1 column for multiple frequency tables with data from the mtcars data set since the OP does not include a reproducible example.
library(arsenal)
lapply(c("cyl","am","carb"),function(x,y){
freqs <- freqlist(table(y[x],useNA = "ifany"))
freq_df <- as.data.frame(freqs)
colnames(freq_df)[1] <- x
freq_df
},mtcars)
...and the output:
[[1]]
cyl Freq cumFreq freqPercent cumPercent
1 4 11 11 34.375 34.375
2 6 7 18 21.875 56.250
3 8 14 32 43.750 100.000
[[2]]
am Freq cumFreq freqPercent cumPercent
1 0 19 19 59.375 59.375
2 1 13 32 40.625 100.000
[[3]]
carb Freq cumFreq freqPercent cumPercent
1 1 7 7 21.875 21.875
2 2 10 17 31.250 53.125
3 3 3 20 9.375 62.500
4 4 10 30 31.250 93.750
5 6 1 31 3.125 96.875
6 8 1 32 3.125 100.000