r - 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。
只需要解决这个问题。
解决方案
我们需要显示相同长度的行/列索引。在这里,我们试图获取单元格在 1, 1, 处的值。行索引是正确的,但列索引是data.frame
一列(ndx[1]
- 基于 OP 帖子中显示的结构)。我们需要提取“V1”列并获取第一个元素作为列索引
predict_all[1, ndx$V1[1]]
#[1] 0.01
注意:我们假设predict_all
为data.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))
推荐阅读
- python - model.compile() 在 keras tensorflow 中做了什么?
- mongodb - MongoDB:当 Primary 关闭时,MongoClient 无法连接到辅助副本集
- css - 如何在 css 中使用此设计逐步创建进度?
- c# - 如何在实际迭代发生之前验证 IAsyncEnumerable 返回方法的参数?
- symfony - Symfony 5.1 的 prod 缓存和禁用它的问题
- vba - Word 2013下的组对象
- java - 如何确定字符串是否不是数组的一部分并计算出现次数?
- react-native - 在两个视图之间反应原生弹性项目
- angular - how to make a custom validator in angular to check a form field based on the other form field?
- javascript - 用户完成保存操作后,从我的网页执行的下载 URL 单击获取文件名?