获取具有条件的元素行 - R

问题描述:

我用一个例子来解释,我插入一个数字(例如,我的输入是2010000),并且需要第三行中的值与我的输入的ccompare总和(我的条件:第三行元素的总和< =我的输入),直到我的条件为真,我需要获取第一行和第二行的值。 例如在201万的情况下,我需要得到获取具有条件的元素行 - 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 Sotos

+0

Thanks @Sotos 。但我想你的答案应该是't_df [1:2,其中(cumsum(t_df $ V3)

您的解决方案也可能会被

#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