hieu hieu - 1 month ago 7
R Question

Take the difference between two columns

I have two data: list contains 271 values and listfull contains 355 values (271 of them are the same as in list). What I want is to print out the 84 different values in these two files. When I write the codes to print the "same" values, they work but not for the "different case". I tried to figure out why but could not. Can you please help me out of this. Thanks

list<-read.table("C:\\Data\\list.txt", header=T)
listfull<-read.table("C:\\Data\\listfull.txt", header=T)



for (i in 1:271)
{
for (j in 1:355)
{
if(list$Cow_ID[i]==listfull$Cow_ID[j])
bo<-data.frame(listfull[j,])

}
write.table(bo,"C:\\Data\\store.txt",row.names = FALSE, dec = ".", na = "NA", sep = " ", append = TRUE, col.names = FALSE)
}


//These above codes work!

//But not the following:

for (i in 1:355)
{
for (j in 1:271)
{
if(listfull$Cow_ID[i]!=listfull$Cow_ID[j])
bo<-data.frame(listfull[i,])

}

write.table(bo,"C:\\Data\\store.txt",row.names = FALSE, dec = ".", na = "NA", sep = " ", append = TRUE, col.names = FALSE)
}


Here how list and listfull look like:

Lisfull List
Cow_ID Cow_ID
26 26
32 32
35 35
219 219
302 302
308 308
383
400
441
445
446
453
462

Answer

You can try setdiff(listfull$Cow_ID, list$Cow_ID).

Eg with some reproducible example:

l1=c(26, 32, 35, 219, 302, 308, 383, 400, 441)
l2=c(26, 32, 35, 219, 302, 308)
setdiff(l1, l2)
> [1] 383 400 441

You could also use %in% or match but it's less straithforward I guess.

Is this what you wanted?