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

后端 未结 2 1263
盖世英雄少女心
盖世英雄少女心 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:17

    It's pretty clear that testd is a dataframe or a list since you didn't get an error from testd$. If you had a testd in which the first element were a number but it was longer than one element you would only have gotten a warning. You perhaps wanted to write:

    avgDeposit <- totalDeposit / 1:nrow(testd)
    

    ... although I admit that doesn't seem very useful. At least it won't throw an error.

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题