1

I am trying to find a way to do 2 things.

  1. Take a dataset and separate it into individual datasets based on its value in a specific variable.

  2. Run each of those datasets through a function using a for() or other statement.

This is a very simple version of what I want I am doing now.

x <- c("Red", "Red", "Red", "Orange", "Blue", "Orange", "Red", "Blue")
y <- c(2,3,1,4,2,6,4,3)
z <- df(x,y) 

Red <- z[z$x == "Red",]
Blue <- z[z$x == "Blue",]
Orange <- z[z$x == "Orange",]

Function1 <- function(x){
  a <- mean(x$y)
  return(a)}

Mean1 <- Function1(Red)
Mean2 <- Function1(Blue)
Mean3 <- Function1(Orange)

Table <- rbind(Mean1, Mean2)
Table <- rbind(Table, Mean3)

Table

I would like to simplify this to automatically create a dataset for each unique 'color', and then run each 'color' dataset through a function.

Appreciate any feedback, thanks!

G5W
  • 32,266
  • 10
  • 31
  • 60
Ghilborn
  • 19
  • 1
  • 4
  • Try running your code before posting please. The first line will throw an error. (Fyi, I'm voting to put your question "on hold" until it's edited to be more answerable.) – Frank Jan 17 '17 at 18:53
  • You should use lists. See my answer at [How to make a list of data frames?](http://stackoverflow.com/a/24376207/903061) for examples. (I'd even recommend closing this as a dupe.) But essentially you do `df_list = split(z, z$x); mean_list = lapply(df_list, Function1); Table = do.call(rbind, mean_list)`. This is very general. In many cases you don't even need lists and can easily use `dplyr` or `data.table` to do things "by group" on your entire dataframe. – Gregor Thomas Jan 17 '17 at 19:01
  • @Frank my apologies, the "'s got dropped when I copied/pasted. – Ghilborn Jan 17 '17 at 19:37
  • Thanks Gregor I will try that. – Ghilborn Jan 17 '17 at 19:38
  • @Gregor Your comment is a decent answer. Why not submit it as such? – Ista Feb 02 '17 at 00:25
  • Thanks for bumping this old question. I think it serves better as a pointer to the List of Data Frames question - everything in my comment is covered there in more detail. – Gregor Thomas Feb 02 '17 at 00:39

0 Answers0