1

I have two dataframes. Dataframe X has 2 columns (k,l)and 15 rows. Data frame Y has 1 row with the same columns.

 X
          k  l
1  17455432  1
2  16590126  2
3  14090453  3
4  20538871  4
5  20935544  5
6  21896196  6
7  14173206  7
8  20193468  8
9  20751149  9
10 23956919 10
11 11295749 11
12 22356733 12
13 20005475 13
14 20035158 14
15  9602016 15

Y
         k l
1  

I want through a loop to save the the row with the smallest value "k" of df X into df Y. I tried :

for (s in 1:15){
  if (s==1){
             Y=X[s,1:2] 
           }else{
             if (X$k[s]>X$k[s-1]){
               Y=X[s-1,1:2] 
             }

           }
}

but this doesn;t work for me. How can I check every time for the value k and keep the row with the min value k in df Y? At first iteration my Y will be the first row of X but then I want to compare the value with the former and keep the row if the value is less than the previous.

g.f.l
  • 39
  • 8
  • 1
    Please consider reading up on [ask] and how to produce a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Makes it easier for others to help you. – Heroka Dec 10 '15 at 08:38
  • Thank you for the min and which.min. This is what I was looking for. – g.f.l Dec 10 '15 at 08:57

1 Answers1

2

There is no need of any loop in R for this (and many others) simple operation. Just try:

Y<-X[which.min(X$k),]
#         k  l
#15 9602016 15

The which.min function gives the index with the minimum value. You use it to subset X as your request.

nicola
  • 24,005
  • 3
  • 35
  • 56
  • I am new in R and I always think for loops. I need to learn about functions because loops sometimes I noticed need time. – g.f.l Dec 10 '15 at 09:01