1

I have a dataset I want split into two datasets - One keeping all the rows of the occurrences happening in the US and the other to be all occurences happening that are Non-US. I have a column made to designate if US 1, else 0 so All rows in US are marked 1 and everything else 0. I want these into two datasets. Here is the example of my dataset

id  variable1  variable2  variable3  Country  US?
1      x           x2         x3        US     1
2      x           x2         x3        US     1
3      x           x2         x3      Mexico   0
4      x           x2         x3        US     1
5      x           x2         x3      Canada   0

and what I'm wanting would look like this, separating into two datasets based on US or not...

US:

id  variable1  variable2  variable3  Country  US?
1      x           x2         x3        US     1
2      x           x2         x3        US     1
4      x           x2         x3        US     1

Non-US:

3      x           x2         x3      Mexico   0
5      x           x2         x3      Canada   0
chrischrischris
  • 57
  • 1
  • 1
  • 6

3 Answers3

0

An option using lapply:

lapply(c(0,1),function(ix) data[data$US? == ix,])

Val
  • 6,585
  • 5
  • 22
  • 52
0

Here's one approach. Assuming your data is stored something like this:

d <- structure(
  list(
    id = 1:5,
    variable1 = c("x", "x", "x", "x", "x"),
    variable2 = c("x2", "x2", "x2", "x2", "x2"),
    variable3 = c("x3",
                  "x3", "x3", "x3", "x3"),
    Country = c("US", "US", "Mexico", "US",
                "Canada"),
    US. = c(1L, 1L, 0L, 1L, 0L)
  ),
  .Names = c("id", "variable1",
             "variable2", "variable3", "Country", "US."),
  class = "data.frame",
  row.names = c(NA,-5L)
)

You can split them up as such:

d1 <- subset(d, US. == 1)
d2 <- subset(d, US. == 0)

And then use the objects however you like.

ssp3nc3r
  • 3,662
  • 2
  • 13
  • 23
0

We can use split into a list of data.frames

lst <- split(df1, df1$`US?`)
akrun
  • 874,273
  • 37
  • 540
  • 662