0
df <- data.frame(cod = c(1,1,2,1,2,2), 
                 nom = c("banana", "banana", "orange", "banana", "orange", "orange"), 
                 val = rnorm(6, 0.06, 0.01))


df <- as.data.table(df)

categol = function(base, col){

      colss = c(paste(col,'_1',sep=''),paste(col,'_2',sep=''))
      base[, colss[1] := 0]
      base[, colss[2] := 0]
      base[as.name(col) == 1, colss[1] := 1]
      base[as.name(col) == 2, colss[2] := 1]

}
categol(df, 'cod')

Unfortunately, this didn't work.

Edward
  • 10,360
  • 2
  • 11
  • 26
  • 1
    Eder, Please make a Minimal Reproducible Example. See https://stackoverflow.com/questions/5963269 . You _must_ include some sample input data; 4-10 lines is usually enough. Include a sample of what you want the output to look like. Don't include images or links to outside data source. We want to help you, but you've got to work with us. – David T May 22 '20 at 03:27
  • Maybe you need to `return(base)` at the end of your function? And assign the result? `df <- categol(df, 'cod')`? It would be easier to help, as David says, if you made it clearer what the goal is. – Gregor Thomas May 22 '20 at 03:30

1 Answers1

1

If you want to do this in data.table, you can use get to get column value from string name.

library(data.table)

categol = function(base, col){
   #Create column names
   cols = paste0(col,'_', 1:2)
   #Initialize them to 0
   base[, (cols) := 0]
   #If col is 1 assign 1 to cols[1]
   base[get(col) == 1, (cols[1]) := 1]
   #If col is 2 assign 1 to cols[2]
   base[get(col) == 2, (cols[2]) := 1] 
   #Return the data
   return(base)
}

Then call categol

out <- categol(df, 'cod')
out
#   cod    nom        val cod_1 cod_2
#1:   1 banana 0.04475522     1     0
#2:   1 banana 0.03908076     1     0
#3:   2 orange 0.05077533     0     1
#4:   1 banana 0.05125148     1     0
#5:   2 orange 0.04395974     0     1
#6:   2 orange 0.05967578     0     1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213