0

I am a beginner in R coding. I have experience with c and c#. I want to check two tables against each other and create new columns with data from the other table. My dataframes are really big and nested for-loops are taking too much time in R. What can I do instead of the following?

    f = as.data.frame(dataset)
    setwd("C:\\Folder\\")
    fnew = read.csv("file.csv", header=TRUE, sep=",")
    f[, 13] <- NA
    f[, 14] <- NA
    f[, 15] <- NA
    f[, 16] <- NA
    for (i in 1:nrow(f))
      {
        for (j in 1:nrow(fnew))
          {
              if (as.character(f[i, 1]) == as.character(fnew[j, 2]))
                  {f[i, 13] = fnew[j, 4]
                   f[i, 14] = fnew[j, 5]
                   f[i, 15] = fnew[j, 6]
                   f[i, 16] = fnew[j, 7]}  
          }
       }
Cettt
  • 11,460
  • 7
  • 35
  • 58
  • 3
    Please review what you can do to provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Ideally you should include (1) minimal & representative sample data in a copy&paste-able format (using e.g. `dput`), (2) a clear problem statement, and (3) your expected output for the sample data you give. That will make it a lot easier for others to understand what it is you're trying to do. At the moment we don't know anything about your data, and have to piece together what you're trying to do based on the code you give. – Maurits Evers Apr 10 '19 at 06:19
  • 1
    If you have a common, unique, identifier then a join will do the job. Coming from a python/mathematica background I found that I needed a completely different mindset when working in R; you will never want to use a loop here. – Paul Apr 10 '19 at 06:30
  • @Paul *"needed a completely different mindset when working in R"* I'm no Python expert but wouldn't you say that Python's `pandas` come with very similar syntax for data manipulation like what's commonly used in R when working with `data.frame`s/`tibble`s in R? – Maurits Evers Apr 10 '19 at 08:09

0 Answers0