Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a IDs with specified column attributes

Tags:

r

The data in which I am trying to make my selection looks like

   ID Field  Rank
8    6 Other  Prof
9    6 Other  Prof
13   7 Other Assoc
16   7 Other Assoc
17   7 Other  Prof
18   8 Other Assoc
19   8 Other Assoc
22   9 Other Assoc
23   9 Other Assoc
24   9 Other  Prof

I am trying to create a new variable that contains all the rows of the people(ID) that have been promoted from 'Assoc' to 'Prof'. For example I would like my new variable to look like

   ID Field  Rank
13   7 Other Assoc
16   7 Other Assoc
17   7 Other  Prof
22   9 Other Assoc
23   9 Other Assoc
24   9 Other  Prof

I have tried the subset function but with no luck.

Is there a function in R that can do this? If not, how can this be achieved.

EDIT: here, is the result from dput(). Note I left out the "Field" variable since it does not contain any information in this example.

 df.promotion <- structure(list(id = c(6, 6, 7, 7, 7, 8, 8, 9, 9, 9), rank = structure(c(2L, 
 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L), .Label = c("Assoc", "Prof"
 ), class = "factor")), .Names = c("id", "rank"), row.names = c(NA, 
 -10L), class = "data.frame")
like image 927
user7045 Avatar asked Feb 23 '23 14:02

user7045


1 Answers

You can use xtabs to tabulate your data by ID and Rank:

tab <- xtabs(~ID+Rank,dfr)
tab
   Rank
ID  Assoc Prof
  6     0    2
  7     2    1
  8     2    0
  9     2    1

You want the ones where no zero occurs:

subset(dfr,ID %in% rownames(tab[as.logical(apply(tab,1,prod)),]))
   ID Field  Rank
13  7 Other Assoc
16  7 Other Assoc
17  7 Other  Prof
22  9 Other Assoc
23  9 Other Assoc
24  9 Other  Prof
like image 92
James Avatar answered Mar 08 '23 15:03

James