如何用我想要的数字替换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))]
是否有任何简单的方法可以在一个地方绘制具有所有这些对应关系的值向量。例如,[对于= = 113 c(0.25,0.50),值= c(10,11,12)] [对于a == 111 c(0.25,0.50,0.75),值= c(1,2, 3,4)] [对于= = 115 c(0.25,0.50,0.75),值= c(1,2,3,4)]都在一个表或框架中,并且每当使用findinterval函数时从这些表中抽取? i列应该被相关的值替换。我想要做的是从另一个文件读取值(例如c(10,11,12))并在需要时放入findinterval函数。
答案 0 :(得分: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添加到结果中。