Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a dummy variable according to data in a matrix in R
    primarykey
    data
    text
    <p>I have a dataframe with 1000 observations belonging to n different countries. Each country has more than 1 observation and the number of observations of each country differ. I need to create a column with numbers going from (1 to n-1), with each number corresponding to a different country. That is, I am creating a dummy variable and I don't care which country has which number. I just need to create such dummies. My data are something like this</p> <pre><code> Region x 1 be1 71615 4 be211 54288 5 be112 51158 6 it213 69856 8 it221 71412 9 uk222 79537 10 de101 94827 11 de10a 98273 12 dea10 92827 .. .. .. </code></pre> <p>Each country has its own "code" in the column Region, for instance beXXXX correpsonds to Belgium, ukXXX to the United Kingdom and so on. Hence I suppose I could exploit the initial <strong>2</strong> letters in the column Region to create my dummies. I know from <a href="https://stackoverflow.com/questions/7562233/how-do-i-select-variables-in-an-r-dataframe-whose-names-contain-a-particular-str">here</a> that the command <code>grep()</code> could do the job, but I need to have a script which automatically switches from 1 to n-1 whenever the initial letters of the Region change.</p> <p>The expected output should be like this</p> <pre><code> Region x Dummy 1 be1 71615 1 4 be211 54288 1 5 be112 51158 1 6 it213 69856 2 8 it221 71412 2 9 uk222 79537 3 10 de101 94827 4 11 de10a 98273 4 12 dea10 92827 4 .. .. .. .. </code></pre> <p>and in this case 1 corresponds to "be" (Belgium), 2 to "it" (Italy) and so on for the ´n´countries in my sample.</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.
 

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