Comparing two files in R and adding the matched rows from one file to another using for loop in R





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have two files. I have read both of the files in data frame in R. "ShortListedGenes" contains 841 genes and "EmpPval" contains 6000 genes. I want to match each gene present in "shortListedGenes" to the genes present in "EmpPval" and extract the relevant information present in the 1st, 2nd and 3rd column of each row (each row represents each gene) in the "EmpPval" file and add it to the "shortListedFile" as new columns. As i am new to R so am using the simple approach and using for loop to get the job done!!! but it's giving the error. The file "shortListedGenes" looks like this



gene    hsq hsq.se  hsq.Pv  ZscoreHsq   PValueZ FDR
ENSG00000198502.5 0.909563 0.018102 0 50.24654734
0 0
ENSG00000225138.3 0.876861 0.018487 0 47.43122194
0 0


The second file "EmpPval" looks like



X   obsExp.perExp   obsExp.Pv   obsExp.perExp.1000  
ENSG00000000460.12 129 0.886162308 0.129
ENSG00000000971.11 268 0.728160071 0.268


So whenever the gene (1st column of both files) matches I want to extract the values for the corresponding gene from the "EmpPval" file and add it to the "shortListedGenes" file.



The code which I have tried till now is:



shortListedGenes <- read.csv("zs7-fdr0.05-Aorta.csv")
EmpPvAl <- read.csv("EmpiricalPvaluesAorta.csv")

for(i in 1:nrow(shortListedGenes))
{
for(j in 1:nrow(EmpPvAl))
{
if(shortListedGenes$gene[i] == EmpPvAl$X[j])
{
shortListedGenes$obsLessExp <- EmpPvAl$obsExp.perExp
shortListedGenes$obsExp <- EmpPvAl$obsExp.Pv
shortListedGenes$obsLessExpDiv <- EmpPvAl$obsExp.perExp.1000
}
}
}


and it is giving the error Error in Ops.factor(EmpPvAl$X, shortListedGenes$gene[i]) : level sets of factors are different



Any suggestion/help would be appreciated!!!. Thanks










share|improve this question





























    0















    I have two files. I have read both of the files in data frame in R. "ShortListedGenes" contains 841 genes and "EmpPval" contains 6000 genes. I want to match each gene present in "shortListedGenes" to the genes present in "EmpPval" and extract the relevant information present in the 1st, 2nd and 3rd column of each row (each row represents each gene) in the "EmpPval" file and add it to the "shortListedFile" as new columns. As i am new to R so am using the simple approach and using for loop to get the job done!!! but it's giving the error. The file "shortListedGenes" looks like this



    gene    hsq hsq.se  hsq.Pv  ZscoreHsq   PValueZ FDR
    ENSG00000198502.5 0.909563 0.018102 0 50.24654734
    0 0
    ENSG00000225138.3 0.876861 0.018487 0 47.43122194
    0 0


    The second file "EmpPval" looks like



    X   obsExp.perExp   obsExp.Pv   obsExp.perExp.1000  
    ENSG00000000460.12 129 0.886162308 0.129
    ENSG00000000971.11 268 0.728160071 0.268


    So whenever the gene (1st column of both files) matches I want to extract the values for the corresponding gene from the "EmpPval" file and add it to the "shortListedGenes" file.



    The code which I have tried till now is:



    shortListedGenes <- read.csv("zs7-fdr0.05-Aorta.csv")
    EmpPvAl <- read.csv("EmpiricalPvaluesAorta.csv")

    for(i in 1:nrow(shortListedGenes))
    {
    for(j in 1:nrow(EmpPvAl))
    {
    if(shortListedGenes$gene[i] == EmpPvAl$X[j])
    {
    shortListedGenes$obsLessExp <- EmpPvAl$obsExp.perExp
    shortListedGenes$obsExp <- EmpPvAl$obsExp.Pv
    shortListedGenes$obsLessExpDiv <- EmpPvAl$obsExp.perExp.1000
    }
    }
    }


    and it is giving the error Error in Ops.factor(EmpPvAl$X, shortListedGenes$gene[i]) : level sets of factors are different



    Any suggestion/help would be appreciated!!!. Thanks










    share|improve this question

























      0












      0








      0








      I have two files. I have read both of the files in data frame in R. "ShortListedGenes" contains 841 genes and "EmpPval" contains 6000 genes. I want to match each gene present in "shortListedGenes" to the genes present in "EmpPval" and extract the relevant information present in the 1st, 2nd and 3rd column of each row (each row represents each gene) in the "EmpPval" file and add it to the "shortListedFile" as new columns. As i am new to R so am using the simple approach and using for loop to get the job done!!! but it's giving the error. The file "shortListedGenes" looks like this



      gene    hsq hsq.se  hsq.Pv  ZscoreHsq   PValueZ FDR
      ENSG00000198502.5 0.909563 0.018102 0 50.24654734
      0 0
      ENSG00000225138.3 0.876861 0.018487 0 47.43122194
      0 0


      The second file "EmpPval" looks like



      X   obsExp.perExp   obsExp.Pv   obsExp.perExp.1000  
      ENSG00000000460.12 129 0.886162308 0.129
      ENSG00000000971.11 268 0.728160071 0.268


      So whenever the gene (1st column of both files) matches I want to extract the values for the corresponding gene from the "EmpPval" file and add it to the "shortListedGenes" file.



      The code which I have tried till now is:



      shortListedGenes <- read.csv("zs7-fdr0.05-Aorta.csv")
      EmpPvAl <- read.csv("EmpiricalPvaluesAorta.csv")

      for(i in 1:nrow(shortListedGenes))
      {
      for(j in 1:nrow(EmpPvAl))
      {
      if(shortListedGenes$gene[i] == EmpPvAl$X[j])
      {
      shortListedGenes$obsLessExp <- EmpPvAl$obsExp.perExp
      shortListedGenes$obsExp <- EmpPvAl$obsExp.Pv
      shortListedGenes$obsLessExpDiv <- EmpPvAl$obsExp.perExp.1000
      }
      }
      }


      and it is giving the error Error in Ops.factor(EmpPvAl$X, shortListedGenes$gene[i]) : level sets of factors are different



      Any suggestion/help would be appreciated!!!. Thanks










      share|improve this question














      I have two files. I have read both of the files in data frame in R. "ShortListedGenes" contains 841 genes and "EmpPval" contains 6000 genes. I want to match each gene present in "shortListedGenes" to the genes present in "EmpPval" and extract the relevant information present in the 1st, 2nd and 3rd column of each row (each row represents each gene) in the "EmpPval" file and add it to the "shortListedFile" as new columns. As i am new to R so am using the simple approach and using for loop to get the job done!!! but it's giving the error. The file "shortListedGenes" looks like this



      gene    hsq hsq.se  hsq.Pv  ZscoreHsq   PValueZ FDR
      ENSG00000198502.5 0.909563 0.018102 0 50.24654734
      0 0
      ENSG00000225138.3 0.876861 0.018487 0 47.43122194
      0 0


      The second file "EmpPval" looks like



      X   obsExp.perExp   obsExp.Pv   obsExp.perExp.1000  
      ENSG00000000460.12 129 0.886162308 0.129
      ENSG00000000971.11 268 0.728160071 0.268


      So whenever the gene (1st column of both files) matches I want to extract the values for the corresponding gene from the "EmpPval" file and add it to the "shortListedGenes" file.



      The code which I have tried till now is:



      shortListedGenes <- read.csv("zs7-fdr0.05-Aorta.csv")
      EmpPvAl <- read.csv("EmpiricalPvaluesAorta.csv")

      for(i in 1:nrow(shortListedGenes))
      {
      for(j in 1:nrow(EmpPvAl))
      {
      if(shortListedGenes$gene[i] == EmpPvAl$X[j])
      {
      shortListedGenes$obsLessExp <- EmpPvAl$obsExp.perExp
      shortListedGenes$obsExp <- EmpPvAl$obsExp.Pv
      shortListedGenes$obsLessExpDiv <- EmpPvAl$obsExp.perExp.1000
      }
      }
      }


      and it is giving the error Error in Ops.factor(EmpPvAl$X, shortListedGenes$gene[i]) : level sets of factors are different



      Any suggestion/help would be appreciated!!!. Thanks







      r






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 3 at 6:06









      StarStar

      116




      116
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You're looking to do a merge (all.x = TRUE, all.y = FALSE):



          shortListedGenes <- merge(shortListedGenes, EmpPvAl[, c("X", "obsExp.perExp",
          "obsExp.Pv", "obsExp.perExp.1000")], by.x = "gene", by.y = "X", all.x = TRUE, all.y = FALSE)


          The issue with your solution is that the variables need to be created first, and you were missing some index notation in the assignment of each of the three new variables:



          # Create variables
          shortListedGenes$obsLessExp <- NA
          shortListedGenes$obsExp <- NA
          shortListedGenes$obsLessExpDiv <- NA

          for(i in 1:nrow(shortListedGenes)){
          for(j in 1:nrow(EmpPvAl)){
          if(shortListedGenes$gene[i] == EmpPvAl$X[j]){
          # Index notation for i and j added:
          shortListedGenes$obsLessExp[i] <- EmpPvAl$obsExp.perExp[j]
          shortListedGenes$obsExp[i] <- EmpPvAl$obsExp.Pv[j]
          shortListedGenes$obsLessExpDiv[i] <- EmpPvAl$obsExp.perExp.1000[j]
          }
          }
          }





          share|improve this answer


























          • Yes, it did work. Thankyou. But can you give some insight why my code was not working? I also tried if(as.character(shortListedGenes$gene[i])) == as.character(EmpPvAl$X[j])) :(

            – Star
            Jan 3 at 7:21











          • @star No worries. I've updated my answer to show you what you were missing. Hopefully you notice some speed improvements from using merge though :-)

            – Khaynes
            Jan 3 at 7:44











          • Yes of course merge is the more efficient way of doing this!!! I wanted to know what I was missing!!! Thankyou so much!!! Much appreciated!! :)

            – Star
            Jan 3 at 8:38












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54017110%2fcomparing-two-files-in-r-and-adding-the-matched-rows-from-one-file-to-another-us%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You're looking to do a merge (all.x = TRUE, all.y = FALSE):



          shortListedGenes <- merge(shortListedGenes, EmpPvAl[, c("X", "obsExp.perExp",
          "obsExp.Pv", "obsExp.perExp.1000")], by.x = "gene", by.y = "X", all.x = TRUE, all.y = FALSE)


          The issue with your solution is that the variables need to be created first, and you were missing some index notation in the assignment of each of the three new variables:



          # Create variables
          shortListedGenes$obsLessExp <- NA
          shortListedGenes$obsExp <- NA
          shortListedGenes$obsLessExpDiv <- NA

          for(i in 1:nrow(shortListedGenes)){
          for(j in 1:nrow(EmpPvAl)){
          if(shortListedGenes$gene[i] == EmpPvAl$X[j]){
          # Index notation for i and j added:
          shortListedGenes$obsLessExp[i] <- EmpPvAl$obsExp.perExp[j]
          shortListedGenes$obsExp[i] <- EmpPvAl$obsExp.Pv[j]
          shortListedGenes$obsLessExpDiv[i] <- EmpPvAl$obsExp.perExp.1000[j]
          }
          }
          }





          share|improve this answer


























          • Yes, it did work. Thankyou. But can you give some insight why my code was not working? I also tried if(as.character(shortListedGenes$gene[i])) == as.character(EmpPvAl$X[j])) :(

            – Star
            Jan 3 at 7:21











          • @star No worries. I've updated my answer to show you what you were missing. Hopefully you notice some speed improvements from using merge though :-)

            – Khaynes
            Jan 3 at 7:44











          • Yes of course merge is the more efficient way of doing this!!! I wanted to know what I was missing!!! Thankyou so much!!! Much appreciated!! :)

            – Star
            Jan 3 at 8:38
















          1














          You're looking to do a merge (all.x = TRUE, all.y = FALSE):



          shortListedGenes <- merge(shortListedGenes, EmpPvAl[, c("X", "obsExp.perExp",
          "obsExp.Pv", "obsExp.perExp.1000")], by.x = "gene", by.y = "X", all.x = TRUE, all.y = FALSE)


          The issue with your solution is that the variables need to be created first, and you were missing some index notation in the assignment of each of the three new variables:



          # Create variables
          shortListedGenes$obsLessExp <- NA
          shortListedGenes$obsExp <- NA
          shortListedGenes$obsLessExpDiv <- NA

          for(i in 1:nrow(shortListedGenes)){
          for(j in 1:nrow(EmpPvAl)){
          if(shortListedGenes$gene[i] == EmpPvAl$X[j]){
          # Index notation for i and j added:
          shortListedGenes$obsLessExp[i] <- EmpPvAl$obsExp.perExp[j]
          shortListedGenes$obsExp[i] <- EmpPvAl$obsExp.Pv[j]
          shortListedGenes$obsLessExpDiv[i] <- EmpPvAl$obsExp.perExp.1000[j]
          }
          }
          }





          share|improve this answer


























          • Yes, it did work. Thankyou. But can you give some insight why my code was not working? I also tried if(as.character(shortListedGenes$gene[i])) == as.character(EmpPvAl$X[j])) :(

            – Star
            Jan 3 at 7:21











          • @star No worries. I've updated my answer to show you what you were missing. Hopefully you notice some speed improvements from using merge though :-)

            – Khaynes
            Jan 3 at 7:44











          • Yes of course merge is the more efficient way of doing this!!! I wanted to know what I was missing!!! Thankyou so much!!! Much appreciated!! :)

            – Star
            Jan 3 at 8:38














          1












          1








          1







          You're looking to do a merge (all.x = TRUE, all.y = FALSE):



          shortListedGenes <- merge(shortListedGenes, EmpPvAl[, c("X", "obsExp.perExp",
          "obsExp.Pv", "obsExp.perExp.1000")], by.x = "gene", by.y = "X", all.x = TRUE, all.y = FALSE)


          The issue with your solution is that the variables need to be created first, and you were missing some index notation in the assignment of each of the three new variables:



          # Create variables
          shortListedGenes$obsLessExp <- NA
          shortListedGenes$obsExp <- NA
          shortListedGenes$obsLessExpDiv <- NA

          for(i in 1:nrow(shortListedGenes)){
          for(j in 1:nrow(EmpPvAl)){
          if(shortListedGenes$gene[i] == EmpPvAl$X[j]){
          # Index notation for i and j added:
          shortListedGenes$obsLessExp[i] <- EmpPvAl$obsExp.perExp[j]
          shortListedGenes$obsExp[i] <- EmpPvAl$obsExp.Pv[j]
          shortListedGenes$obsLessExpDiv[i] <- EmpPvAl$obsExp.perExp.1000[j]
          }
          }
          }





          share|improve this answer















          You're looking to do a merge (all.x = TRUE, all.y = FALSE):



          shortListedGenes <- merge(shortListedGenes, EmpPvAl[, c("X", "obsExp.perExp",
          "obsExp.Pv", "obsExp.perExp.1000")], by.x = "gene", by.y = "X", all.x = TRUE, all.y = FALSE)


          The issue with your solution is that the variables need to be created first, and you were missing some index notation in the assignment of each of the three new variables:



          # Create variables
          shortListedGenes$obsLessExp <- NA
          shortListedGenes$obsExp <- NA
          shortListedGenes$obsLessExpDiv <- NA

          for(i in 1:nrow(shortListedGenes)){
          for(j in 1:nrow(EmpPvAl)){
          if(shortListedGenes$gene[i] == EmpPvAl$X[j]){
          # Index notation for i and j added:
          shortListedGenes$obsLessExp[i] <- EmpPvAl$obsExp.perExp[j]
          shortListedGenes$obsExp[i] <- EmpPvAl$obsExp.Pv[j]
          shortListedGenes$obsLessExpDiv[i] <- EmpPvAl$obsExp.perExp.1000[j]
          }
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 3 at 7:43

























          answered Jan 3 at 6:26









          KhaynesKhaynes

          727721




          727721













          • Yes, it did work. Thankyou. But can you give some insight why my code was not working? I also tried if(as.character(shortListedGenes$gene[i])) == as.character(EmpPvAl$X[j])) :(

            – Star
            Jan 3 at 7:21











          • @star No worries. I've updated my answer to show you what you were missing. Hopefully you notice some speed improvements from using merge though :-)

            – Khaynes
            Jan 3 at 7:44











          • Yes of course merge is the more efficient way of doing this!!! I wanted to know what I was missing!!! Thankyou so much!!! Much appreciated!! :)

            – Star
            Jan 3 at 8:38



















          • Yes, it did work. Thankyou. But can you give some insight why my code was not working? I also tried if(as.character(shortListedGenes$gene[i])) == as.character(EmpPvAl$X[j])) :(

            – Star
            Jan 3 at 7:21











          • @star No worries. I've updated my answer to show you what you were missing. Hopefully you notice some speed improvements from using merge though :-)

            – Khaynes
            Jan 3 at 7:44











          • Yes of course merge is the more efficient way of doing this!!! I wanted to know what I was missing!!! Thankyou so much!!! Much appreciated!! :)

            – Star
            Jan 3 at 8:38

















          Yes, it did work. Thankyou. But can you give some insight why my code was not working? I also tried if(as.character(shortListedGenes$gene[i])) == as.character(EmpPvAl$X[j])) :(

          – Star
          Jan 3 at 7:21





          Yes, it did work. Thankyou. But can you give some insight why my code was not working? I also tried if(as.character(shortListedGenes$gene[i])) == as.character(EmpPvAl$X[j])) :(

          – Star
          Jan 3 at 7:21













          @star No worries. I've updated my answer to show you what you were missing. Hopefully you notice some speed improvements from using merge though :-)

          – Khaynes
          Jan 3 at 7:44





          @star No worries. I've updated my answer to show you what you were missing. Hopefully you notice some speed improvements from using merge though :-)

          – Khaynes
          Jan 3 at 7:44













          Yes of course merge is the more efficient way of doing this!!! I wanted to know what I was missing!!! Thankyou so much!!! Much appreciated!! :)

          – Star
          Jan 3 at 8:38





          Yes of course merge is the more efficient way of doing this!!! I wanted to know what I was missing!!! Thankyou so much!!! Much appreciated!! :)

          – Star
          Jan 3 at 8:38




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54017110%2fcomparing-two-files-in-r-and-adding-the-matched-rows-from-one-file-to-another-us%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith