-4

I'm new to R. I have a dataset with names in the first row, the category the names belong to in the second row, and then price observations for two year from the third row onwards. I want to split the data frame using the categories in the second row. How do I do this?

This is what my dataset looks like (on R):

enter image description here

This is what I want it look like (on Excel) : enter image description here

Note: I cannot do this on Excel and then import because there are way too many categories.

amonk
  • 1,769
  • 2
  • 18
  • 27
phil_t
  • 851
  • 2
  • 7
  • 17
  • I do not think so, I did read that post before asking this question. The problem is the structure of the dataset. I have added a capture of what my dataset looks like. – phil_t Mar 27 '17 at 15:27
  • Post a capture of what ur expecting too. Not able to understand your end requirement. – Jil Jung Juk Mar 27 '17 at 15:28
  • Posted the end requirement capture. – phil_t Mar 27 '17 at 15:35
  • @phil_t, your question is just not in the right format. Can you please check [this post](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – InspectorSands Mar 27 '17 at 16:43

2 Answers2

0

Multiple possiblities

df <- data.frame(data = c(1:12), category = rep(letters[1:3], 4))
  1. subset function.

    df_a <- subset(df, category == "a")
    
  2. basic data.frame subset

    df_a <- df[df$category == "a",]
    
  3. into a list

    ls <- list
    for(category in unique(df$category)){
       ls[[category]] <- df[df$category == "a", ]
    } 
    
  • I am not able to use subset or your other suggestions because the category does not have a row name. I have added a capture of what my dataset looks like as of now. I am not sure I can add a row name for the second row. – phil_t Mar 27 '17 at 15:24
0

You have the answer in your question. The split or split.data.frame functions would do it. The second argument must be of factor type for this to work.

Example

newdf <- split.data.frame(iris, iris$Species)
newdf
Jil Jung Juk
  • 690
  • 2
  • 9
  • 21
  • I am not able to use split because the category does not have a row name. I have added a capture of what my dataset looks like as of now. I am not sure I can add a row name for the second row. – phil_t Mar 27 '17 at 15:23