Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting data by type in R

Tags:

types

sorting

r

I am struggling to write a function for a dataset that looks like this:

identifier   age   occupation        
pers1        18    student   
pers2        45    teacher   
pers3        65    retired   

What I am trying to do, is to write a function that will:

  1. sort my variables into numerical vs. factor variable
  2. for the numerical variables, give me the mean, min and mx
  3. for the factor variable, give me a frequency table
  4. return point (2) and (3) in a "nice" format (dataframe, vector or table)

So far, I have tried this:

describe<- function(x) 
{ if (is.numeric(x)) { mean <- mean(x)
                   min <- min(x)
                   max <- max(x) 
                   d <- data.frame(mean, min, max)}
  else { factor <- table(x) }
}
stats <- lapply(data, describe)

Problems: My problem is that now, "stats" is a list that is difficult to read and to export to Excel or share. I don't know how to make the list "stats" more reader-friendly.

Alternatively, maybe is there a better way to build the function "describe"?

Any thoughts on how to solve these two problems are much appreciated!

like image 767
cremorna Avatar asked Sep 12 '26 10:09

cremorna


1 Answers

I ma be late to the party, but maybe you still need a solution. I combined the answers from some of the comments to your post to the following code. It assumes you only have numerical columns and factors, and scales to a large number of columns, as you specified:

# Just some sample data for my example, you don't need ggplot2.
library(ggplot2)
data=diamonds

# Find which columns are numeric, and which are not.
classes = sapply(data,class)
numeric = which(classes=="numeric")
non_numeric = which(classes!="numeric")

# create the summary objects    
summ_numeric = summary(data[,numeric])
summ_non_numeric = summary(data[,non_numeric])

# result is easily written to csv
write.csv(summ_non_numeric,file="test.csv")

Hope this helps.

like image 189
Florian Avatar answered Sep 14 '26 23:09

Florian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!