swchen swchen - 26 days ago 23
R Question

Subset the data based on a unique value in R

I have a data below

test=data.frame("name"=c("A","A","A","A","B","B","C"), value=c(10,11,12,13,14,15,16))


I want to subset the test data based on non-repeated name "C", I want to show the data below:

name value
c 16


I try
test[table(test$name)>1,]
, but the output was wrong.

Please give me some hint, thanks!!

Answer

using data.frame as such,

table.freq <- as.data.frame(table(test$name))
test[test$name %in% table.freq$Var1[table.freq$Freq==1],]
#  name value
#7    C    16

or using which

test[test$name %in% names(which(table(test$name)==1)),]
#  name value
#7    C    16