2012-12-12 91 views
-1

如何用我想要的數字替換findinterval函數的結果?下面是dput()輸出:R中的findInterval函數(設置結果)

a=c(113,113,113,113,111,111,115,116,117,118,220,220) 
b=c(113,113,113,113,111,111,115,116,117,118,220,220) 
c=c(2,2,1,1,5,1,1,2,1,1,1,4) 
d=c(2,2,12,12,15,12,12,2,12,12,12,14) 
e=c(1,1,1,1,1,2,2,2,2,2,2,3) 
f=c(20,30,25,35,45,55,60,65,70,75,75,80) 
h=c("1A","1A","2A","3A","1A","5A","4A","4A","7A","7A","9A","9A") 
i=c(12,16,17,19,20,15,18,17,17,13,14,15) 

m=data.frame(a=a,b=b,c=c,d=d,e=e,f=f,h=h,i=i) 

dput(m) 
structure(list(a = c(113, 113, 113, 113, 111, 111, 115, 116, 
117, 118, 220, 220), b = c(113, 113, 113, 113, 111, 111, 115, 
116, 117, 118, 220, 220), c = c(2, 2, 1, 1, 5, 1, 1, 2, 1, 1, 
1, 4), d = c(2, 2, 12, 12, 15, 12, 12, 2, 12, 12, 12, 14), e = c(1, 
1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3), f = c(20, 30, 25, 35, 45, 55, 
60, 65, 70, 75, 75, 80), h = structure(c(1L, 1L, 2L, 3L, 1L, 
5L, 4L, 4L, 6L, 6L, 7L, 7L), .Label = c("1A", "2A", "3A", "4A", 
"5A", "7A", "9A"), class = "factor"), i = c(12, 16, 17, 19, 20, 
15, 18, 17, 17, 13, 14, 15)), .Names = c("a", "b", "c", "d", 
"e", "f", "h", "i"), row.names = c(NA, -12L), class = "data.frame") 

set.seed(5) 
m$rand <- runif(nrow(m)) 

m[a==113,"i"] <- c(10,11,12)[1+findInterval(unlist(m[m$a==113,"rand",with=F]),c(0.25,0.50))] 

有沒有什麼簡單的方法,從具有所有這些信件在一個地方值向量繪圖。例如,對於== 113 c(0.25,0.50),values = c(10,11,12)] [for a == 111 c(0.25,0.50,0.75),values = c(1,2, 3,4)] [對於== 115 c(0.25,0.50,0.75),values = c(1,2,3,4)]都在一個表或框架中,並且每當findinterval函數被使用時從這些繪製出來? i列應該被相關的值替換。我想要做的是從另一個文件讀取值(例如c(10,11,12)),並在需要時放入findinterval函數。

+0

如果您忽略大部分data.table語法和內存效率,爲什麼還要使用data.table?你想要的數字是什麼? – mnel

+0

它給了我錯誤,而不使用data.table。期望的數字是10和11(對於小於0.45的數字,得到數字10,對於大於0.45的rand,得到數字11)。我將爲表格的其他部分使用相同的過程。 – Kaveh

+0

你是從這些數字中拉出來的? – mnel

回答

1

0和1是findInterval正在返回的內容。這一結果應該用來索引你感興趣的值嘗試:

> k[a==113,"WWW"] <- c(10,11)[1+findInterval(unlist(k[k$a==113,"rand",with=F]),c(0.45))] 
# or draw from the values vector based on your comment 
# (which should instead be an edit rather than a comment. 
values=c(10,11,12) 
k[a==113,"WWW"] <- values[1+findInterval(unlist(k[k$a==113,"rand",with=F]),c(0.45))] 
> k 
    a b c d e WWW  rand 
1: 113 2 2 1 20 10 0.2002145 
2: 113 2 2 1 30 11 0.6852186 
3: 112 1 12 1 25 17 0.9168758 
4: 114 1 12 1 35 19 0.2843995 

由於載體的基礎,而不是從零開始1,您需要將1添加到結果。

+0

謝謝迪文。這解決了我的問題。有沒有什麼簡單的方法可以從一個具有所有這些對應關係的值向量中繪製出來。例如,對於a == 112 c(0.25,0.50),values = c(10,11,12)] [for a == 114 c(0.25,0.50,0.75),values = c(1,2, 3,4)] a == 114 c(0.25,0.50,0.75),values = c(1,2,3,4)]都在一個表或框架中,並且每當findinterval函數被使用時從這些中抽取出來? – Kaveh

+0

從該數據框中發佈dput()的輸出,我們可能有更好的機會實際計算出您實際正在處理的內容。 –

+0

當然,我將它添加到問題窗口中。謝謝! – Kaveh