2016-09-29 4 views
0

예를 들어 번호를 삽입합니다 (예 : 입력 2010000). 제 입력의 3 행에 값의 합이 필요합니다 (내 조건 : 세 번째 행의 요소 합계 < = 내 입력) 내 조건이 True가 될 때까지 첫 번째와 두 번째 행에서 값을 가져와야합니다. 는 2,010,000의 경우 예를 들어, 나는조건이있는 요소 행을 얻습니다. - R

1 2 3 4 
-1 -1 -1 -1 

P.S을 얻을 필요가 : 나는 세 번째 행의 마지막 양의 값을 읽을 수 있습니다.

나는 for loops와 함께 할 수 있지만, 당신이 알고있는 루프는

감사

내 데이터 R. 빠른되지 않습니다

1  2  3  4  10  37  NA 
-1  -1  -1  -1  -1  -1  -6 
549493 217514 732961 506807 113712 139339 2259826 
+0

데이터가 (http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) 내가 생각 – Sotos

+0

는 쉽게 [재현] 될 것이다되지 않는다 만약 당신이 데이터 세트 ('t_df <- as.data.frame (t (df))')를 옮기고't_df [which (cumsum (t_df $ V3) <= 2010000), 1 : 2]' – Sotos

+0

@Sotos . 하지만 당신의 대답은't_df [1 : 2, (cumsum (t_df $ V3) <= 2010000)]'이어야한다고 생각합니다. :) –

답변

0

귀하의 솔루션을 가능하게 할 수

#setting up a data frame with your data structure 
row1 <- c(1,2,3,4,10,37,NA) 
row2 <- c(-1,-1,-1,-1,-1,-1,-6) 
row3 <- c(549493,217514,732961,506807,113712,139339,2259826) 

df <- rbind(row1,row2,row3) 

#generating a row4 with sums upto that point 
row4 <- sapply(1:length(df[3,]),function(x) sum(df[3,1:x])) 

#your input 
input <- c(2010000) 

#logical vector where your condition is reached 
row5 <- row4<input 

#index where the summation is <= input 
index <- min(which(row5 == FALSE)) 

#your results 
answer_row1 <- row1[1:index] 
answer_row2 <- row2[1:index] 

#youv can format your results which ever way you want now that you 
#have the value of #index 

이 작동하는지 알려주세요.

Lune3141

관련 문제