0

x is a data.frame

id  income  age 
1   23246  21
1   12455  45
3   24555  31
2   10045  42

I would like to have 3 data frames based on id number

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
Y.esk
  • 11
  • 3

2 Answers2

1

split(x,x$id) will produce a list of data frames split on id.

George Savva
  • 4,152
  • 1
  • 7
  • 21
  • I am sorry, it looks trivial, but I want to save the results of corresponding values for each id in a data frame. Like a loop or sth does it to get the result x1 <- 23246 21 12455 45 x2<- 10045 42, x3<- 24555 31 – Y.esk Feb 24 '20 at 21:53
  • 1
    @Y.esk It is advisable to store the splitted `data.frame`s in a `list` (rather than as "loose" objects in your environment). The `split` command generates a `list`, which then can be conveniently processed/manipulated using functions from the `*apply` family. – Maurits Evers Feb 24 '20 at 21:57
0

I guess what you need is list2env, i.e.,

xs <- split(x,x$id)
list2env(setNames(xs,paste0("df",names(xs))),
         envir = .GlobalEnv)

which creates data frames df1, df2 and df3 in your global environment, such that

> df1
  id income age
1  1  23246  21
2  1  12455  45
> df2
  id income age
4  2  10045  42
> df3
  id income age
3  3  24555  31
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • 1
    No, this is not good R coding practice! Instead of having loose objects floating around in your global environment it is much better/safer to store the objects in a `list`. It will also make accessing/manipulating the sub-`data.frame`s much more straightforward using `lapply`/`sapply` etc. – Maurits Evers Feb 24 '20 at 22:02
  • @MauritsEvers then `xs <- split(x, x$id)` would be enough – ThomasIsCoding Feb 24 '20 at 22:03
  • Yes, see the first answer by @GeorgeSavva. – Maurits Evers Feb 24 '20 at 22:04