r - Subset a data.frame based on row-column combinations
问题描述
I want to subset a data.frame based on subscripts stored in another data.frame.
So for example, if I have the following data.frame:
set.seed(1)
x <- rnorm(5)
df <- data.frame(x,x*x, x*2, x/2)
df
x x...x x...2 x.2
1 -0.6264538 0.39244438 -1.2529076 -0.31322691
2 0.1836433 0.03372487 0.3672866 0.09182166
3 -0.8356286 0.69827518 -1.6712572 -0.41781431
4 1.5952808 2.54492084 3.1905616 0.79764040
5 0.3295078 0.10857537 0.6590155 0.16475389
I want to subset the values of [1,3] and [2,4]. Thus the data.frame which I want to use as keys for subsetting looks like this:
sub <- data.frame(row = c(1,2), col = c(3,4))
sub
row col
1 1 3
2 2 4
My result should look like this:
c(df[1,3], df[2,4])
[1] -1.25290762 0.09182166
However, it should all be done within one df[*]
I know this is easy but I still cannot figure it out! So thanks a lot in advance.
解决方案
将其转换为matrix
子集
df[as.matrix(sub)]
#[1] -1.25290762 0.09182166
推荐阅读
- r - 忽略 ggplot 中 geom_bar 和 geom_histogram 中的异常值
- ms-access - 要求 ID 参数的表单的嵌入式报告
- java - 在 Spring boot 中添加超过 65535 个条目的 jar
- java - @Entity 将 null passworld 发送到 h2 db
- java - 如何使用 Firebase 搜索查询结果项实现 OnClick 项
- entity-framework - 如何使用 Fluent Api 使我的结构与 EF Core 一起工作?
- ssl - 检查 API 协议以确保没有停机时间
- javascript - HTML选择下拉列表如何显示VALUE/ID而不是文本
- acumatica - 如何从重定向页面刷新网格
- python - Python:如果列具有键值对格式的数据,如何读取 csv 数据