Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is another solution, using <code>strsplit</code>:</p> <pre><code># The data df.1 = read.table(header=TRUE, text=" color identifier blue 'A1, B2, C3, C4' yellow 'B2, C4, C6' green 'A3'", stringsAsFactors = FALSE) df.2 = read.table(header=FALSE, text=" A1 Mercedes A3 BMW B2 Porsche C3 Toyota C4 Hundai C5 Volkswagen C6 Peugeot", stringsAsFactors=FALSE) names(df.2) = c("identifier", "car") df.1$identifier = strsplit(df.1$identifier, split=", ") df.1$identifier1 = lapply(1:nrow(df.1), function(x) df.2[which(df.2$identifier %in% df.1$identifier[[x]]), 2]) df.1 # color identifier identifier1 # 1 blue A1, B2, C3, C4 Mercedes, Porsche, Toyota, Hundai # 2 yellow B2, C4, C6 Porsche, Hundai, Peugeot # 3 green A3 BMW </code></pre> <p>Note that <code>identifier</code> and <code>identifier1</code> are now <em>lists</em> in your <code>data.frame</code>. I personally find this easier to work with later on.</p> <pre><code>str(df.1) # 'data.frame': 3 obs. of 3 variables: # $ color : chr "blue" "yellow" "green" # $ identifier :List of 3 # ..$ : chr "A1" "B2" "C3" "C4" # ..$ : chr "B2" "C4" "C6" # ..$ : chr "A3" # $ identifier1:List of 3 # ..$ : chr "Mercedes" "Porsche" "Toyota" "Hundai" # ..$ : chr "Porsche" "Hundai" "Peugeot" # ..$ : chr "BMW" </code></pre> <p>You may need to modify the <code>strsplit</code> if there is any whitespace left over, but it works with this sample data. Also, for <code>strsplit</code> to work, the data need to be in mode <code>as.character</code> (hence my use of <code>stringsAsFactors</code> when reading in the data).</p> <h1>Update: write.table()</h1> <p>I <em>do</em> prefer to keep the data in lists in case I wanted to do further analysis. However, if the data are complete or just for output purposes, you might want to do something like this:</p> <pre><code>df.3 = df.1 df.3$identifier = sapply(df.3$identifier, paste0, collapse=", ") df.3$identifier1 = sapply(df.3$identifier1, paste0, collapse=", ") </code></pre> <p>This will allow you to use <code>write.table</code> since <code>identifier</code> and <code>identifier1</code> are now of mode <code>character</code> instead of <code>list</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload