Extract rows with unique value in one column and equal to text "NA" in another column using R

StackOverflow https://stackoverflow.com/questions/23233051

  •  07-07-2023
  •  | 
  •  

Pergunta

Given a data.frame with 3 columns, A, B, C:

A    B       C
P   NA   black
W    4   white
F    6   black
R   NA    pink
H    8    blue
V   NA  yellow

Using R, I would like to figure out how to extract rows with a unique value in column C AND text "NA" in column B.

So in this case, the row being extracted should be row 4 and 6.

Foi útil?

Solução

subset(dat, !duplicated(C) & !duplicated(C, fromLast=T) & is.na(B))
#   A  B      C
# 4 R NA   pink
# 6 V NA yellow

Outras dicas

If your column B stores strings "NA" do this

dat[ave(rep(1,nrow(dat)), dat$C, FUN=sum)==1 & dat$B=="NA",]

if it stores actual NA values (missing values), do this

dat[ave(rep(1,nrow(dat)), dat$C, FUN=sum)==1 & is.na(dat$B),]

where dat is your dataframe. The result:

  A  B      C
4 R NA   pink
6 V NA yellow
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top