2012-04-08 28 views
6

我在R中有一個數字向量,它包含負數和正數。我想基於符號(忽略現在零)在列表中的號碼,分離成兩個單獨列出:R:從一個向量中選擇與條件匹配的項目

  • 一個新的向量僅包含負數
  • 含有的另一種載體只有正數

該文檔顯示瞭如何在數據框中選擇行/列/單元格 - 但這不適用於向量AFAICT。

如何做(沒有for循環)?

+0

原來,我可以簡單地在選擇條件中使用矢量的名稱中使用。例如:negs < - temp [temp <0] – 2012-04-08 20:32:41

回答

10

這是非常容易做到(楠補充檢查):

d <- c(1, -1, 3, -2, 0, NaN) 

positives <- d[d>0 & !is.nan(d)] 
negatives <- d[d<0 & !is.nan(d)] 

如果你想排除雙方NA和NaN的,is.na()兩個返回true:

d <- c(1, -1, 3, -2, 0, NaN, NA) 

positives <- d[d>0 & !is.na(d)] 
negatives <- d[d<0 & !is.na(d)] 
+0

如何忽略選擇中的NaNs? – 2012-04-08 21:16:45

+0

我編輯了答案。請注意,d> 0是邏輯模式的向量,對於is.nan(d)和is.na(d)也是如此。對邏輯模式的兩個向量應用「邏輯」。 – 2012-04-08 21:53:25

+0

謝謝,你是明星! – 2012-04-08 21:56:08

1

它可以通過使用「方括號」來完成。 將創建一個包含大於零的值的新矢量。由於使用了比較運算符,它將以布爾值表示值。因此方括號用於得到確切的數值。

d_vector<-(1,2,3,-1,-2,-3) 
new_vector<-d_vector>0 
pos_vector<-d_vector[new_vector] 
new1_vector<-d_vector<0 
neg_vector<-d_vector[new1_vector] 
0

purrr封裝包括一些有用的功能,用於濾波載體:

library(purrr) 
test_vector <- c(-5, 7, 0, 5, -8, 12, 1, 2, 3, -1, -2, -3, NA, Inf, -Inf, NaN) 

positive_vector <- keep(test_vector, function(x) x > 0) 
positive_vector 
# [1] 7 5 12 1 2 3 Inf 

negative_vector <- keep(test_vector, function(x) x < 0) 
negative_vector 
# [1] -5 -8 -1 -2 -3 -Inf 

還可以discard功能

相關問題