-1

如何用我想要的数字替换 findinterval 函数的结果?下面是 dput() 输出:

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))]

是否有任何简单的方法可以从一个具有所有这些对应关系的值向量中提取。例如有 [for a==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)] [for a==115 c(0.25,0.50,0.75),values=c(1,2,3,4)] 都在一个表格或框架中,并在使用 findinterval 函数时从中绘制?i 列应该被相关的值替换。我想要做的是从另一个文件中读取值(例如 c(10,11,12)),并在需要时放入 findinterval 函数。

4

1 回答 1

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 添加到结果中。

于 2012-12-12T23:43:17.160 回答