数据表 - 从另一列按名称选择列的值 [英] Data Table - Select Value of Column by Name From Another Column

查看:19
本文介绍了数据表 - 从另一列按名称选择列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表,其中包含许多包含值的列.我有另一列定义了我需要选择哪些列的值.我很难找到一种方法来做到这一点.

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.

这是一个简单的例子.

> 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

我想添加一个列value.of.col",其中包含name.of.col"指定的列的值.

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

推荐答案

另一种选择:

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添加更快的解决方案:

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

这篇关于数据表 - 从另一列按名称选择列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆