从列中提取负值

时间:2013-04-15 07:33:47

标签: r integer

我已经在一个包含5列和200行的表格中读到了 R - 我希望在我的第五列中具有负值的十行向量中的索引 - 是某种方式可能的?

我的桌子叫做r。 我知道我可以通过以下方式提取第五行:

r[,5]

但我不知道如何排除所有正值,或者在列中获取负值的索引

1 个答案:

答案 0 :(得分:3)

# *** Get some test data ***
> con <- textConnection(Lines <- "
+ First, Last, Email, CustomerSince, Balance, RiskFactor
+ Alan, Appleton, aa@google.com,1992, -100,  3
+ Bob, Bates, BobB@yahoo.com,1997, 231,  2
+ Charles, Clemson, Chuck@Clemson.com,2001, -4.2,  1
+ Dennis, Delgado, dd@hotmail.com,2004, 27,  1
+ Ernesto, Ellonka, Ernie@hotmail.com,2010, 40.5,  6
+ ")
> x <- read.csv(con)
> close(con)
# *** That's what our data looks like.  5th column is numeric
> x
    First      Last              Email CustomerSince Balance RiskFactor
1    Alan  Appleton      aa@google.com          1992  -100.0          3
2     Bob     Bates     BobB@yahoo.com          1997   231.0          2
3 Charles   Clemson  Chuck@Clemson.com          2001    -4.2          1
4  Dennis   Delgado     dd@hotmail.com          2004    27.0          1
5 Ernesto   Ellonka  Ernie@hotmail.com          2010    40.5          6

# *** And here's how to get a vector of all indexes of the Balance column
# *** that have a negative value
> x["Balance"] < 0
     Balance
[1,]    TRUE
[2,]   FALSE
[3,]    TRUE
[4,]   FALSE
[5,]   FALSE
> 
# *** And here's how to directly exclude the positive balance from the list
> x[x$Balance < 0, ]
First      Last              Email CustomerSince Balance RiskFactor
1    Alan  Appleton      aa@google.com          1992  -100.0          3
3 Charles   Clemson  Chuck@Clemson.com          2001    -4.2          1

# to just get the list of indexes that match that criteria, you can use which()
> which(x$Balance < 0)
[1] 1 3