Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

r - Data Table - Select Value of Column by Name From Another Column

I have a data table with a number of columns containing values. I have another column which defines which one of those columns whose value I need to select. I am having trouble finding a way to do this.

Here is a simple example.

> d <- data.table(
     value.1 = c("one", "uno", "1"),
     value.2 = c("two", "dos", "2"),
     name.of.col = c("value.1","value.2","value.1"))

> d
   value.1 value.2 name.of.col
1:     one     two     value.1
2:     uno     dos     value.2
3:       1       2     value.1

I would like to add a column 'value.of.col' which contains the value of the column specified by 'name.of.col'.

> d
   value.1 value.2 name.of.col  value.of.col
1:     one     two     value.1  one
2:     uno     dos     value.2  dos
3:       1       2     value.1  1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another option:

d[ , value.of.col := diag(as.matrix(.SD)), .SDcols = d[ , name.of.col]]
> d
   value.1 value.2 name.of.col value.of.col
1:     one     two     value.1          one
2:     uno     dos     value.2          dos
3:       1       2     value.1            1

EDIT add a faster solution:

d[ , value.of.col :=
      melt(d,id.vars='name.of.col')[name.of.col==variable, value]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...