r - add a column in data table using for loop -


i have data.table called md looks this

group_1 group_2       b       b       b c       c 

i use following code: groups <- c("group_1","group_2")

    (group in groups)     {      md[!get(group)=="a",get(group):="b"]      md[,get(group):=factor(x = get(group),levels = c("a","b"),ordered = t)]     } 

so want both columns in data.table if value every row not "a" replace value "b" , add ordered levels it.

but error error in get(group): object 'group_1' not found

any ideas ?

another option using set

 for(group in groups){    set(md, = which(md[[group]] !='a'), j = group, value = 'b')     set(md, = null, j = group, value = factor(md[[group]], levels = c('a', 'b'),       ordered = true)) } md #    group_1 group_2 #1:             #2:       b       #3:       b       b #4:       b       b 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -