首页 > 解决方案 > R从数据表中提取值给定存储在另一个表中的索引

问题描述

我有一个向量(ndx)和表(predict_all)

向量 ndx 包含预测所有表的索引

ndx 如下:

V1 
1  
4  
5  
6 

predict_all 数据表如下:

V1   V2   V3   V4   V5   V6
0.01 0    0.2  0.4  0.1  0
0.2  0.01 0.1  0.3  0.6  0.3

[...]

当我这样做时: predict_all[1,1]我得到 0.01,但如果我这样做predict_all[1, ndx[1]],我应该得到 0.01 时得到 1。

只需要解决这个问题。

标签: rvector

解决方案


我们需要显示相同长度的行/列索引。在这里,我们试图获取单元格在 1, 1, 处的值。行索引是正确的,但列索引是data.frame一列(ndx[1]- 基于 OP 帖子中显示的结构)。我们需要提取“V1”列并获取第一个元素作为列索引

predict_all[1, ndx$V1[1]]
#[1] 0.01

注意:我们假设predict_alldata.frame

如果是data.table,则使用with = FALSE

predict_all[1, ndx$V1[1], with = FALSE]
#    V1
#1: 0.01

数据

ndx <- structure(list(V1 = c(1L, 4L, 5L, 6L)), .Names = "V1", 
 class = "data.frame", row.names = c(NA, -4L))

predict_all <- structure(list(V1 = c(0.01, 0.2), V2 = c(0, 0.01), 
 V3 = c(0.2, 0.1), V4 = c(0.4, 0.3), V5 = c(0.1, 0.6), 
 V6 = c(0, 0.3)), .Names = c("V1", 
 "V2", "V3", "V4", "V5", "V6"), class = "data.frame",
 row.names = c(NA, -2L))

推荐阅读