Skip to content
Prev 316516 / 398506 Next

Fastest way to compare a single value with all values in one column of a data frame

Hi,
Any chance x$a to have the same number repeated?

If `Item` and `a` are unique,? I guess both the solutions should work.

set.seed(1851)
x<- data.frame(item=sample(letters[1:20],20,replace=F),a=sample(1:45,20,replace=F),b=sample(20:50,20,replace=F),stringsAsFactors=F)
y<- data.frame(item="z",a=3,b=10,stringsAsFactors=F)

x[intersect(which(x$a < y$a),which.min(x$a)),]
?#? item a? b
#17??? c 1 48
?x[x$a==which.min(x$a[x$a<y$a]),]
#?? item a? b
#17??? c 1 48
#or 

x[x$a%in%which.min(x$a[x$a<y$a]),]
#?? item a? b
#17??? c 1 48

x[x$a%in%which.min(x$a[x$a<y$a]),]<-y

tail(x)
#?? item? a? b
#15??? q 45 30
#16??? g 10 23
#17??? z? 3 10
#18??? r 15 39
#19??? l 18 45
#20??? t 35 33

#However, if `item` column is unique, but `a` is not, then the one I mentioned previously arise.
set.seed(1851)
x1<- data.frame(item=sample(letters[1:20],20,replace=F),a=sample(1:10,20,replace=T),b=sample(20:50,20,replace=F),stringsAsFactors=F)
y1<- data.frame(item="z",a=3,b=10,stringsAsFactors=F)


x1[intersect(which(x1$a < y1$a),which.min(x1$a)),]
?# item a? b
#3??? s 1 41
x1[x1$a==which.min(x1$a[x1$a<y1$a]),]
?#? item a? b
#3???? s 1 41
#11??? h 1 46
#17??? c 1 48
x1[x1$a==which.min(x1$a[x1$a<y1$a]),]<- y1
A.K.