R Error: “In numerical expression has 19 elements: only the first used”

后端 未结 2 1265
盖世英雄少女心
盖世英雄少女心 2021-01-18 21:34

I created a dataframe:

totalDeposit <- cumsum(testd$TermDepositAMT[s1$ix])

which is basically calculating cumulative sum of TermDeposit

2条回答
  •  天涯浪人
    2021-01-18 22:22

    The error message is, in this case, helpful.

    When you say 1:N, what you're telling R is "give me the sequence of integers between 1 and N". It's from integer1 to integer2. testd isn't an integer, it's (at best) an entire vector of integers, and so R disposes of all but the first value in testd when calculating the sequence. The alternative would be either a horrible error or a set of sequences - one between 1 and the first value in testd, another between 1 and the second value in testd...and so on.

    What you want instead is 1:nrow(testd), if testd is a data frame, and either 1:length(testd) or seq_along(testd) if it's a list or vector.

    Based on the question, though - the need to calculate averages? - you're actually approaching this wrong, because you don't want a sequence of values, you just want one: since average = total/number of elements that went into that total, you just want 'the number of elements' - which can be retrieved simply with nrow(testd).

提交回复
热议问题