2013-08-05 2 views
1

제목이 다소 절름발이라는 것을 알고 있지만 이것을 다른 것으로 부를 수는 없습니다. lon (경도 열)에 나타나는 값을 사용하여 큰 데이터 프레임의 하위 집합을 만들려고합니다. 내가 현재 가지고있는 부분 집합 스크립트는 작동하며 -180 (n/a 값)이 나타날 때마다 하위 집합을 만들고 하나 이상의 -180이 존재하기 전후의 첫 번째 -180이 아닌 숫자를 포함합니다. 내 문제는 하위 집합이 -180 년대 이전에 20 개의 경도로 구성되고 20 개 이후로 구성되기를 바랍니다. 많은 파일들이 -180 초부터 시작하여 -180 초로 끝나기 때문에 이것은 생성과 오류입니다. 나는 스크립트가 -180을 부분 집합하는 방법을 알지 못하지만 첫 번째 또는 마지막 행에 나타날 수도있는 것을 무시하는 방법도 모른다. 이상적으로 스크립트는 20 개의 경도와 20 개의 경도가있는 -180을 하위 집합으로 만 구성합니다. 또한 파일의 시작과 끝 부분에 -180이 얼마나 많이 나타날지를 결코 알지 못할 것입니다. 이것은 자신을 알아내는 데있어 가장 큰 문제점이었습니다. 아래는 나의 데이터 샘플과 현재 서브 세팅 코드입니다. 당신의 도움에 미리 감사드립니다! 편집 : 행이 동일한 순서로 유지되고 이것이 연대순 데이터이므로 어떤 식 으로든 정렬되지 않도록하는 것이 매우 중요합니다. 그리고 내 데이터 프레임에는 4461 개의 행과 7 개의 열이 있습니다. 아래의은 내 데이터 프레임의 작은 샘플입니다.전후에 20 행을 포함하도록 데이터 프레임을 서브 세트로 작성

cols <- structure(list(fixType = structure(c(39L, 39L, 39L, 39L, 39L, 39L, 39L, 39L, 39L, 39L), .Label = c("firstfix +indoors +startpoint", "firstfix +indoors +startpoint +cluster_center", "firstfix +indoors +stationary", "firstfix +indoors +stationary +cluster_center", "firstfix +invehicle +startpoint", "firstfix +invehicle +startpoint +cluster_center", "firstfix +invehicle +stationary +cluster_center", "firstfix +outdoors +startpoint", "firstfix +outdoors +startpoint +cluster_center", "firstfix +outdoors +stationary", "firstfix +outdoors +stationary +cluster_center", "inserted +indoors +midpoint", "inserted +indoors +pausepoint", "inserted +indoors +stationary", "inserted +indoors +stationary +cluster_center", "inserted +invehicle +midpoint", "inserted +invehicle +pausepoint", "inserted +invehicle +stationary", "inserted +invehicle +stationary +cluster_center", "inserted +outdoors +midpoint", "inserted +outdoors +pausepoint", "inserted +outdoors +stationary", "inserted +outdoors +stationary +cluster_center", "lastfix +indoors +endpoint", "lastfix +indoors +endpoint +cluster_center", "lastfix +indoors +stationary", "lastfix +indoors +stationary +cluster_center", "lastfix +invehicle +endpoint", "lastfix +invehicle +endpoint +cluster_center", "lastfix +outdoors +endpoint", "lastfix +outdoors +endpoint +cluster_center", "lastfix +outdoors +stationary", "lastvalidfix +indoors +stationary", "lastvalidfix +indoors +stationary +cluster_center", "lastvalidfix +invehicle +stationary", "lastvalidfix +invehicle +stationary +cluster_center", "lastvalidfix +outdoors +stationary", "lastvalidfix +outdoors +stationary +cluster_center", "unknown", "valid +indoors +endpoint", "valid +indoors +endpoint +cluster_center", "valid +indoors +midpoint", "valid +indoors +pausepoint", "valid +indoors +pausepoint +cluster_center", "valid +indoors +startpoint", "valid +indoors +startpoint +cluster_center", "valid +indoors +stationary", "valid +indoors +stationary +cluster_center", "valid +invehicle +endpoint", "valid +invehicle +endpoint +cluster_center", "valid +invehicle +midpoint", "valid +invehicle +pausepoint", "valid +invehicle +startpoint", "valid +invehicle +startpoint +cluster_center", "valid +invehicle +stationary", "valid +invehicle +stationary +cluster_center", "valid +outdoors +endpoint", "valid +outdoors +endpoint +cluster_center", "valid +outdoors +midpoint", "valid +outdoors +pausepoint", "valid +outdoors +pausepoint +cluster_center", "valid +outdoors +startpoint", "valid +outdoors +startpoint +cluster_center", "valid +outdoors +stationary", "valid +outdoors +stationary +cluster_center"), class = "factor"), lon = c(-180, -180, -180, -180, -180, -180, -180, -180, -180, -180), lat = c(-180, -180, -180, -180, -180, -180, -180, -180, -180, -180), activityIntensity = c(2L, 2L, 1L, 2L, 2L, 2L, 0L, 2L, 1L, 0L), Impute = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), ID = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 4352L, 4353L, 4354L), subsetNum = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("fixType", "lon", "lat", "activityIntensity", "Impute", "ID", "subsetNum"), row.names = c(4462L, 4463L, 4464L, 4465L, 4466L, 4467L, 4468L, 8813L, 8814L, 8815L), class = "data.frame") 

부분 번호 :

set.seed(5) 
n <- length(df) #make it equal to the length of whatever the input file is 

impCols <- df[ , c("fixType", "lon", "lat", "activityIntensity", "Impute", "ID", "subsetNum")] 

test.df <- data.frame(impCols) 

df <- test.df 
obs <- dim(df)[1] 

counter <- 1 
subM.List <- list() 

start.idx <- NA 

for(i in 1:obs){ 
    if (is.na(start.idx) & (substr(df[i,"lon"], 1, 4) == -180)){ 
     start.idx <- i-1 
    } 
    else if (!is.na(start.idx) & (substr(df[i,"lon"], 1, 4) != -180)){ 
    end.idx <- i+1 #the plus one will give you the first two instances of signal instead of just the first 
    subMat <- df[start.idx:end.idx,] 
    subM.List[[counter]] <- subMat 
    start.idx <- NA 
    counter <- counter + 1 
    } 
} 
+1

맥스'같은 것을 사용을 고려한다 (I, 20) '와'분 (I, nrow (데이터)) '/ 시작의 선택을 종료 귀하의 20 행. – user12202013

+0

@EllisValentiner 행의 순서가 연대순임을 언급해야하며, 내 응용 프로그램의 경우 행의 순서를 유지하는 것이 매우 중요합니다. 나는 현재 min과 max를 시도하고있다. 그러나 아마 그것이 내 행의 순서를 바꿀 것이라고 생각한다. – Misc

+2

여기에서'diff (lon == 180)'은 당신의 친구입니다. 'df' 데이터를 위해 특별히 [재현 가능한 예제] (http://bit.ly/SORepro)를 게시 할 수 있다면 매우 유용 할 것입니다. –

답변

0
indicators <- df$lon == -180 

# the first and last non-zero indicators are your index boundaries 
indx.min <- min(which(!indicators)) # will issue warning if lon is nothing but '-180' 
indx.max <- max(which(!indicators)) # will issue warning if lon is nothing but '-180' 

"My problem is that I would like the subsets to be comprised of 
    the 20 longitudes before any -180s, and 20 after" 


# `inPlay` are the indicators that are not at the extreme ends 
inPlay <- which(indicators) 
inPlay <- inPlay[inPlay > indx.min & inPlay < indx.max] 

# Sample Size 
S <- 20 # use a variable so you can change it as needed 

diffPlay <- diff(inPlay) 
stop <- c(which(diffPlay !=1), length(inPlay)) 
start <- c(1, which(diffPlay !=1)+1) 

# these are your rowranges of `180s`. You can have a look if youd like 
rbind(inPlay[start], inPlay[stop]) 

# we are going to take the 20 rows before each "start" 
# and the 20 rows after each "start" + "plus" 
inPlayPlus <- inPlay[stop] - inPlay[start] 
inPlayStart <- inPlay[start] 

## The names given to `inPlay` will be the name of your subsetted list 
names(inPlayStart) <- ifelse(inPlayPlus > 0, paste0("Rows", inPlayStart, "_to_", inPlayStart+inPlayPlus), paste0("Row", inPlayStart)) 

subsetsList <- 
    lapply(seq_along(inPlayStart), function(i) { 
     # This can be one line. Broken up so you can see what's happening 
     from <- max(indx.min, inPlayStart[[i]]-S) # notice, calling max on the min 
     to <- min(indx.max, inPlayStart[[i]] + inPlayPlus[[i]] +S) # and min on the max 

     cat("i is ", i, "\tPlus=", inPlayPlus[[i]], "\t(from, to) = (", from, ", ", to, ")\tDIFF=", to-from, "\n", sep="") 
     indx <- if (inPlayPlus[[i]] == 0) from:to else setdiff(from:to, inPlayStart[[i]]+(1:inPlayPlus[[i]])) 
     df[indx, ] 
    }) 


## Have a look at the results 
subsetsList 
+0

예, 맞습니다. 내 의견에 놀래기 :-). 하지만, 심각한 측면에서,이 대답은 단지 행의 한 블록이 -180으로 위 아래로 묶여 있음을 발견합니다. 그렇죠? 저는 4600 개의 행 중에서 그 블록이 몇 개 있다는 것을 추측하고 있습니다. 따라서 생각하는 '최소'및 '최대'표시기 이상을 찾아야합니다. –

+0

@CarlWitthoft,'lapply' 문을보세요. -180의 각 항목을 반복합니다. 최소/최대의 유일한 목적은 시작/종료 시리즈를 제외하는 것입니다. –

+0

@RicardoSaporta 이것은 실행되었지만 너무 많은 335 개의 하위 집합 (4461 개의 행 중에서)을 제공했으며 각 하위 집합은 41 개의 행으로 구성되었으며 그 중 하나가 일련의 행으로 구성되었습니다. 아직 무엇이 잘못되었는지는 모르겠지만 다른 것들을 시도하고 있습니다. – Misc

관련 문제