1

I have list of variable names in a vector of strings v and a data table my.dt that contains all these variables.

> v

[1] "var1" "var2" "var3"

I want to use those variables whose names are in the vector v, such that i create new variable that is cbind of these 3, or any number of names that appear in v, like:

  new <- cbind(my.dt[,"var1"],my.dt[,"var2"],my.dt[,"var3"])
new1 <- rowSums(new, na.rm=TRUE) * ifelse(rowSums(is.na(new)) == ncol(new), NA, 1)

How can i get this, having in mind that number of variables is not fixed, so i dont want to refer to each element like v[1], v[2] etc.

5
  • 1
    Perhaps my.dt[, v] ? Commented Oct 13, 2018 at 22:36
  • i dont think its working... Commented Oct 13, 2018 at 22:52
  • And you didn't provide a reproducible example, so guessing is the only thing I can do. Commented Oct 13, 2018 at 22:57
  • For example, this small example produces the same error to me:my.dt = data.table( ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c = 13:18 ) v <- c("a", "ID") my.dt[, v] Commented Oct 13, 2018 at 23:06
  • No one knows you are working on a data.table because you did not mention it. The quality of your post is poor. Next time, please provide relevant information and reproducible example so others can better help you. Commented Oct 13, 2018 at 23:24

1 Answer 1

1

Based on your comment, you are working on a data.table. You will need to add with = FALSE to the code as follows.

library(data.table)

my.dt <- data.table( ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c = 13:18 ) 
v <- c("a", "ID") 

my.dt[, v, with = FALSE]
#    a ID
# 1: 1  b
# 2: 2  b
# 3: 3  b
# 4: 4  a
# 5: 5  a
# 6: 6  c

Notice that if you are working on a data frame, you don't need with = FALSE.

my.dt <- data.frame( ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c = 13:18 ) 
v <- c("a", "ID") 

my.dt[, v]
#   a ID
# 1 1  b
# 2 2  b
# 3 3  b
# 4 4  a
# 5 5  a
# 6 6  c
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.