2

I have a data.table called md that looks like this

group_1 group_2
a       a
b       a
b       b
c       c

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

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

So I want for both columns in the data.table if the value for every row is not "a" then replace the value with "b" and then add ordered levels to it.

But I get an error Error in get(group): object 'group_1' not found

Any ideas ?

4
  • The get(group) := should be just group := Commented Mar 28, 2017 at 10:02
  • but then it adds a column called group, whereas i want to replace the values at the existing columns Commented Mar 28, 2017 at 10:04
  • 1
    It needs (group) := Commented Mar 28, 2017 at 10:08
  • 1
    it worked. thanks :) Commented Mar 28, 2017 at 10:16

1 Answer 1

1

Another option is using set

 for(group in groups){
   set(md, i = which(md[[group]] !='a'), j = group, value = 'b')
    set(md, i = NULL, j = group, value = factor(md[[group]], levels = c('a', 'b'),
      ordered = TRUE))
}
md
#    group_1 group_2
#1:       a       a
#2:       b       a
#3:       b       b
#4:       b       b
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.