r中的存在和不存在映射

时间:2013-06-28 06:26:54

标签: r

我正在尝试为缺席和存在生成0和1。我的数据是线段,我必须绘制0或1,间隔为0.1,对于位于线段内的点或线段外的点。

    V1   V2   V3  V4        V5 V6 V7
3   17 26.0 26.0  0 12-Jun-84  1  0
4   17 48.0 48.0  1 12-Jun-84  3  0
5   17 56.7 56.7  0 12-Jun-84  1  0
143 17 16.3 16.3  0 19-Jun-84  1  8
144 17 17.7 17.7  0 19-Jun-84  1  8
145 17 22.0 22.0  0 19-Jun-84  1  8

v2v3是起点和终点,v4是它们之间的分隔。

我试过了

tran17 <- seq(0, 80, by=0.1)
tran17.date1 <- rep(0, length(tran17))
##
sub1 <-which(tran17 >= c$V2[i] & tran17 <= c$V3[i])
tran17.date1[sub1] <- 1

三江源

2 个答案:

答案 0 :(得分:1)

忽略您的数据示例并专注于您的问题,我认为这解决了问题。另外,如果V1是分组因素,则可以tapply使用PAmatrix

# test data
sed.seed(1104) 
dat = data.frame(V1=17, V2=runif(200, 10, 60))
dat$V3 = dat$V2 + runif(200, 0, 20)
dat$V4 = dat$V3 - dat$V2

  V1       V2       V3         V4
1 17 37.25826 45.54194  8.2836734
2 17 17.44098 22.86841  5.4274331
3 17 49.78488 55.51627  5.7313965
4 17 51.66640 52.54813  0.8817293
5 17 21.84276 39.38477 17.5420079
6 17 53.39457 54.51613  1.1215530

# functions to solve the problem
isInside = function(limits, tran) as.numeric(tran>=limits[1] & tran<=limits[2])
PAmatrix = function(data, tran) t(apply(data, 1, isInside, tran=tran))

# calculate the PA matrix
tran17 = seq(0, 80, by=0.1)
PA17 = PAmatrix(data=dat[,c("V2","V3")], tran=tran17)

# plot the results
image(seq(nrow(dat)), tran17, PA17, col=c("blue", "red"))

theplot

答案 1 :(得分:0)

tran17 <- seq(0, 80, by=0.1)

tran17.date1&lt; - rep(0,length(tran17))

dm&lt; - (c $ V5 ==“31-Jul-84”)

for(i in dm){   打印(I)   sub1&lt; -which(tran17&gt; = c $ V2 [i]&amp; tran17&lt; = c $ V3 [i])   tran17.date1 [sub1]&lt; - 1

}

plot(tran17,tran17.date1)