如何通过R的data.table中的另一列中的内容选择列? [英] How to select the columns by the content in another column in data.table of R?

查看:157
本文介绍了如何通过R的data.table中的另一列中的内容选择列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据表:

I have a data.table like this:

> dt<-data.table(F=rep(c('a','b','c'),each=2), fix=c(10:15),a=c(1:6), b=c(2:7),c=c(3:8))
> dt
   F fix a b c
1: a  10 1 2 3
2: a  11 2 3 4
3: b  12 3 4 5
4: b  13 4 5 6
5: c  14 5 6 7
6: c  15 6 7 8

列F存储每行要提取的列。因此,对于前两个记录列,将提取3和4记录的 a列,而提取 b列。每条记录都会保留修复程序。理想的输出应该是这样的:

The column F stores the column to be extract for each row. So for the first 2 records column, the column 'a' will be extract while the column 'b' will be extracted for the 3 and 4 record. The 'fix' will be kept for each record. The ideal output should be like this:

   F  fix new
1: a  10   1 
2: a  11   2
3: b  12   4
4: b  13   5
5: c  14   7
6: c  15   8


推荐答案

您可以使用 .BY 提取列来自 .SD

You can use .BY to extract the column from .SD

dt[, .(fix = fix, new = .SD[[.BY$F]]), by = F]
##    F fix new
## 1: a  10   1
## 2: a  11   2
## 3: b  12   4
## 4: b  13   5
## 5: c  14   7
## 6: c  15   8

这篇关于如何通过R的data.table中的另一列中的内容选择列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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