2

我不确定如何在没有错误的情况下执行此操作。这是我的问题的简化示例。

假设我有这个数据框 DF

a   b  c  d
1   2  3  4
2   3  4  5
3   4  5  6

然后我有一个变量

x <- min(c(1,2,3))

现在我想做以下事情

y <- DF[a == x]

但是,当我尝试引用诸如“x”之类的变量时,会出现错误,因为 R 正在我的数据框中查找列“x”。我收到“选择了未定义的列”错误

我怎样才能在 R 中做我想做的事情?

4

2 回答 2

4

You may benefit from reading an Introduction to R, especially on matrices, data.frames and indexing. Your a is a column of a data.frame, your x is a scalar. The comparison you have there does not work.

Maybe you meant

R> DF$a == min(c(1,2,3))
[1]  TRUE FALSE FALSE
R> DF[,"a"] == min(c(1,2,3))
[1]  TRUE FALSE FALSE
R> 

which tells you that the first row fits but not the other too. Wrapping this in which() gives you indices instead.

于 2010-04-03T19:18:36.150 回答
2

我想这就是你要找的:

> x <- min(DF$a)
> DF[DF$a == x,]
  a b c d
1 1 2 3 4

一种更简单的方法(避免使用“x”变量)是:

> DF[which.min(DF$a),]
  a b c d
1 1 2 3 4

或这个:

> subset(DF, a==min(a))
  a b c d
1 1 2 3 4
于 2010-04-05T14:01:45.580 回答