0

I'm doing if condition and I want to match values from 2 different columns and of they match it has to assign value to another column. when I write the statement

for (l in 1:k) { 
  for(i in 1:n) { 
    if(y_related[i,2]==con_f[l]) {
      y_out[l]=y_related[i,1] 
    }
  }
} 

then it doesn't work! but if I replaced the con_f with it's numerical value say 0.004 then it works. but I wanted to run it automatically as I don't want to write the numerical value every time!!

detailed example:

y_related=matrix(NA,1000,2) 
y_related[,1]=rnorm(1000,5,10) 
y_related[,2]=rank(y_related[,1])/1000 
con_f=matrix(NA,250,1) 
for(x in 1:250) { 
  con_f[x]=(1-((x-1)/250))
}
y_out=matrix(NA,250,1) 
for (l in 1:250) { 
  for(i in 1:1000) { 
    if(y_related[i,2]==con_f[l]) {
      y_out[l]=y_related[i,1]
    }
   }
}
Tensibai
  • 15,557
  • 1
  • 37
  • 57
Hanan
  • 33
  • 1
  • 5
  • 1
    Please add some code to your issue to make it reproducible. – slava-kohut Sep 20 '19 at 13:21
  • y_related=matrix(NA,1000,2) y_related[,1]=rnorm(1000,5,10) y_related[,2]=rank(y_related[,1])/1000 con_f=matrix(NA,250,1) for(x in 1:250){con_f[x]=(1-((x-1)/250))} y_out=matrix(NA,250,1) for (l in 1:250){for(i in 1:1000){if(y_related[i,2]==con_f[l]){y_out[l]=y_related[i,1]}}} – Hanan Sep 20 '19 at 13:36
  • @slava-kohut there is always problem at l=17 and 18 for example even though that they have match in y_related[,2] – Hanan Sep 20 '19 at 13:38
  • please modify your initial post – slava-kohut Sep 20 '19 at 13:59
  • I don't get any error running your detailed example, how does it "not work" ? – Tensibai Sep 20 '19 at 14:43

1 Answers1

0

This sounds like a job for the function merge

# Turn them in to data frames, and rename to sensible names
y_related_df <- as.data.frame(y_related)
names(y_related_df) <- c("value", "variable")
con_f_df <- as.data.frame(con_f)
names(con_f_df) <- c("variable")

# merge allows you to join on a vector of variables, and then move the data from
# y in to x as we've done a left join (all.x=TRUE)
output <- merge(x=con_f_df, y=y_related_df, by="variable", all.x=TRUE)
output

If you're not familiar with different types of joins, then have a look at this stackoverflow post

merge is very very useful, I use it all the time

Jonny Phelps
  • 2,687
  • 1
  • 11
  • 20