Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

data.table

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
like image 959
Nick Allen Avatar asked Jan 30 '14 19:01

Nick Allen


People also ask

How do you find the value of one column in another column in Excel?

You can use the MATCH() function to check if the values in column A also exist in column B. MATCH() returns the position of a cell in a row or column. The syntax for MATCH() is =MATCH(lookup_value, lookup_array, [match_type]) . Using MATCH, you can look up a value both horizontally and vertically.

How can you identify a column in a DataTable?

By using the Column name or Column index we can identify a column in a data table.

How can get column data from DataTable in jquery?

var myTable = $("#tblResults"). DataTable(); var resultsArray = myTable. columns(colIndex). data();


1 Answers

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]]
like image 161
agstudy Avatar answered Sep 30 '22 14:09

agstudy