3

I would like to re-order my data according to a specific simple pattern.

I would simply like to re-arrange my data with one row Female, one row Male, in keeping householdid one after another.

The data look like this :

  householdid.x    idno   isex iage
1        101366 1013661 FEMALE   29
2        101366 1013662   MALE   36
3        102481 1024812   MALE   39
4        102481 1024811 FEMALE   29
5        103755 1037552   MALE   36
6        103755 1037551 FEMALE   31

I can't figure out how to do this.

Let us say that FEMALE comes first. The output I am looking for is simply:

  householdid.x    idno   isex iage
1        101366 1013661 FEMALE   29
2        101366 1013662   MALE   36
4        102481 1024811 FEMALE   29
3        102481 1024812   MALE   39
6        103755 1037551 FEMALE   31
5        103755 1037552   MALE   36

The data

dta = structure(list(householdid.x = c("101366", "101366", "102481", 
"102481", "103755", "103755"), idno = c(1013661, 1013662, 1024812, 
1024811, 1037552, 1037551), isex = structure(c(1L, 2L, 2L, 1L, 
2L, 1L), .Label = c("FEMALE", "MALE"), class = "factor"), iage = structure(c(22L, 
29L, 32L, 22L, 29L, 24L), .Label = c(" 8", " 9", "10", "11", 
"12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", 
"23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", 
"34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", 
"45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", 
"56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", 
"67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", 
"78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", 
"89", "90", "91", "92", "93", "94", "95", "98"), class = "factor")), .Names = c("householdid.x", 
"idno", "isex", "iage"), row.names = c(NA, 6L), class = "data.frame")
giac
  • 3,673
  • 2
  • 19
  • 47

1 Answers1

4

If there is only one male and female per household, then you can just do:

dta <- dta[order(dta$householdid.x, dta$isex), ]

Which gives the desired output:

  householdid.x    idno   isex iage
1        101366 1013661 FEMALE   29
2        101366 1013662   MALE   36
4        102481 1024811 FEMALE   29
3        102481 1024812   MALE   39
6        103755 1037551 FEMALE   31
5        103755 1037552   MALE   36

And if I'm not mistaken, this was the 100,000th question with the r tag!

maccruiskeen
  • 2,638
  • 2
  • 11
  • 23
  • oh yeah ? where can I see this `100,000th question with the r tag` ? – giac Jul 22 '15 at 16:34
  • 1
    Well it doesn't actually say so but if you click on the `r` tag it tells you how many questions are tagged `r` in the sidebar. This was 100,000 when you asked your question. But if questions asked before you got removed since, then it won't be the 100,000th any more. – maccruiskeen Jul 22 '15 at 16:45