r - 选择具有指定列属性的 ID

标签 r

我试图在其中进行选择的数据看起来像

   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")

最佳答案

您可以使用 xtabs通过 ID 制表您的数据和 Rank :

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

你想要没有零出现的那些:
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

关于r - 选择具有指定列属性的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7888412/

相关文章:

html - 在 R markdown 中嵌入现有的 HTML

R - 基于多个条件匹配来自 2 个数据帧的值(当查找 ID 的顺序是随机的时)

r - 将因子水平应用于缺少因子水平的多个列

r - 使用infile bash语法运行Docker

r - 对比只能应用于因子

r - 根据条件从大数据表中的每个组中选择一行

r - 创建一个 data.frame,其中一列是一个列表

r - 警告信息 : Removed 4 rows containing missing values (geom_path) 的含义

r - 无法向空数据表添加值

r - 是否需要从基本包中显式导入 roxygen?