1

I would like to create multiple DFs, where each new DF only contains observations for that student. Currently, I create a new DF using the following code. Which I repeat, changing the students name.

James <- All_Results [which(All_Results$`Student.x` =='James'),]

DF: All_Results

 Student  Score_Jan  Score_Feb  Score Mar
 James       12          76          23
 James       52          86          63     
 James       19          74          83
 Nick        72          26          54
 Nick        92          16          43
 Nick        12          76          23
 Tony        87          36          52
 Tony        22          46          33

How can I do this if I have the following

 c(James, Nick, Tony)

Any help is appreciated

CISCO
  • 539
  • 1
  • 4
  • 14

1 Answers1

2

If the length of the vector is greater than or equal to 1, %in% is an option

newdat <- All_Results[All_Results$`Student.x` %in% c('James', 'Nick', 'Tony'),]

It would also take care of the NA elements, so there is no need to wrap with which


If the intention is to create separate data.frames, then use split

lst1 <- split(All_Results, All_Results$`Student.x`)

If we want only a subset of elements, then use the 'newdat' created earlier

lst1 <- split(newdat, new$`Student.x`)

It will return a list of data.frames. It is not advisable to create multiple data.frame objects in the global environment. But, it can be done with assign or list2env

list2env(lst1, .GlobalEnv)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @skrun - Thank you very much for your help. I keep getting the following error "Error in new$student : object of type 'closure' is not subsettable" – CISCO Aug 12 '19 at 06:20
  • @CISCO. Can you check the `str` of your data. I assume that it is a normal column – akrun Aug 12 '19 at 12:52
  • 1
    Thanks @akrun - that was the proble, All fixed up now. – CISCO Aug 12 '19 at 23:34