附加列表循环

append list for loop

我无法弄清楚我在将循环结果(作为小标题)附加到列表中时做错了什么。 下面是代码。我相信这与距离的 d 和数字不是正数有关? 数据列表 [[d]] <- dat 中的错误: 尝试 select 小于 integerOneIndex

中的一个元素
library(tidyverse)


x <-  c(10,5)
y <-  c(1,3)
distance <- c(1,2,3)   # distance away from the road

old<-data.frame(x,y)

datalist = list()
datalist2 = list()



for (d in 1: length(distance)) {
  # Given a vector (defined by 2 points) and the distance, 
  # calculate a new vector that is distance away from the original 
  segment.shift <- function(x, y, d){
    
    # calculate vector
    v <- c(x[2] - x[1],y[2] - y[1])
    
    # normalize vector
    v <- v/sqrt((v[1]**2 + v[2]**2))
    
    # perpendicular unit vector
    vnp <- c( -v[2], v[1] )
    
    return(list(x =  c( x[1] + d*vnp[1], x[2] + d*vnp[1]), 
                y =  c( y[1] + d*vnp[2], y[2] + d*vnp[2])))
    
  }
  
  
  # allocate memory for the bike path
  xn <- numeric( (length(x) - 1) * 2 )
  yn <- numeric( (length(y) - 1) * 2 )
  
  for ( i in 1:(length(x) - 1) ) {
    xs <- c(x[i], x[i+1])
    ys <- c(y[i], y[i+1])
    new.s <- segment.shift( xs, ys, d )
    xn[(i-1)*2+1] <- new.s$x[1] ; xn[(i-1)*2+2] <- new.s$x[2]
    yn[(i-1)*2+1] <- new.s$y[1] ; yn[(i-1)*2+2] <- new.s$y[2]
  }

  

  dat1<-as_tibble()
  dat1<-as.data.frame(xn)%>%mutate(id=row_number())%>%mutate(Dist_Col=paste(d,"left",sep="_"))
  #datalist[[d]] <- dat1 # add it to your list
  
  dat2<-as_tibble()
  dat2<-as.data.frame(yn)%>%mutate(id=row_number())%>%mutate(Dist_Col=paste(d,"left",sep="_"))
  #datalist2[[d]] <- dat2 # add it to your list
  
  
  ###Now do right side
  
  # allocate memory for the bike path
  xn <- numeric( (length(x) - 1) * 2 )
  yn <- numeric( (length(y) - 1) * 2 )
  
  for ( i in 1:(length(x) - 1) ) {
    xs <- c(x[i], x[i+1])
    ys <- c(y[i], y[i+1])
    new.s <- segment.shift( xs, ys, -d )
    xn[(i-1)*2+1] <- new.s$x[1] ; xn[(i-1)*2+2] <- new.s$x[2]
    yn[(i-1)*2+1] <- new.s$y[1] ; yn[(i-1)*2+2] <- new.s$y[2]
  }
  
  
  dat3<-as_tibble()
  dat3<-as.data.frame(xn)%>%mutate(id=row_number())%>%mutate(Dist_Col=paste(d,"right",sep="_"))
  
  datcomb<- full_join(dat1,dat3)
  
  datalist[[d]] <- datcomb # add it to your list
  
  dat4<-as_tibble()
  dat4<-as.data.frame(yn)%>%mutate(id=row_number())%>%mutate(Dist_Col=paste(d,"right",sep="_"))
  
  dat2comb<- full_join(dat2,dat4)
  datalist2[[d]] <- dat2comb # add it to your list
  
  
  
  
  }

big_data = do.call(rbind, datalist)
big_data2 = do.call(rbind, datalist2)


comb_data<- full_join(big_data,big_data2)

ggplot()+geom_line(data=old,aes(x,y),color='black')+geom_line(data=comb_data,aes(xn,yn,group=Dist_Col),color='red')

查看上面更新的代码,在原始线的两侧绘制平行线。

我终于用

解决了这个问题
for (d in 1:length(distance)) 

剧情更新