In R how do I compare values in a row of a dataframe by a single value in the same row of another dataframe

Viewed 18

I have two tables as follows:

mydata<-data.frame(ID=1:50,value=runif(n=50))
head(mydata)
ID value
1 0.59057316
2 0.11036060
3 0.84050703

The other is a dataframe comprising 50 rows and 100 columns of random numbers:

rntable<-as.data.frame(matrix(runif(n=5000, min=0, max=1),nrow=50))
head(rntable)
n v1 v2 v3 v4
1 0.21092575 0.68144251 026929378 0.34583023
2 0.42875037 0.09916910 0.46925 0.6598
3 0.13268998 0.11890256 0.1718 0.31178

The requirement:

  • Compare each row of rntable to the value in the same row of mydata
  • Where the values of rntable are lower than mydata$value, output 0, else 1

The output should be a third table that looks like this:

n v1 v2 v3 v4
1 0 1 0 0
2 1 0 1 1
3 0 0 0 0

Importantly, the comparison is per row.

I imagine I have to loop by row. But I don't know if I should first merge the tables (and if I did, column names would get messy). Is there an easy way in R to run this comparison?

I tried the following overly simple comparison but the output was all 1's.

x<-ifelse(rntable<mydata$value,0,1)

Thanks

1 Answers

I found the answer by playing with the code:

datac<-rntable #simple way to copy table structure

for(i in 1:nrow(mydata)) {
  for(j in 1:ncol(rntable)) {
    datac[i,j]<-rntable[i,j]<mydata[i,2]  
  }
}

This results in the table as required.

Related