【问题标题】:get the elements row with a condition - R获取具有条件的元素行 - R
【发布时间】:2016-09-29 14:43:58
【问题描述】:

我用一个例子解释,我插入一个数字(例如,我的输入是 2010000)并且我需要将第三行中的值的总和与我的输入进行比较(我的条件:第三行中元素的总和)行

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

【问题讨论】:

  • 您的数据不是reproducible
  • 我认为如果你转置你的数据集(t_df <- as.data.frame(t(df)))并做t_df[which(cumsum(t_df$V3) <= 2010000), 1:2]
  • 谢谢@Sotos。但我猜你的答案应该是t_df[1:2,which(cumsum(t_df$V3) <= 2010000)]。 :)
  • 不。我转置了数据框,所以它是正确的

标签: r


【解决方案1】:

您的解决方案可能是

#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

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多