R for loop not working

后端 未结 3 1473
予麋鹿
予麋鹿 2020-12-22 08:41

I\'m trying to use R to find the max value of each day for 1 to n days. My issue is there are multiple values in each day. Heres my code. After I run it incorrect number of

3条回答
  •  一生所求
    2020-12-22 08:54

    Unlike other programming languages, in R it is considered good practice to avoid using for loops. Instead try something like:

    index <- sapply(Days, function(x) {
        which.max(Value)
    })
    theData[index, c("Day", "Time", "Value")]
    

    This means for each value of Days, find the maximum value of Value and return its index. Then you can select the rows and columns of interest.

    I recommend reading the help documentation for apply(), lapply(), sapply(), tapply(), mapply() (I'm probably forgetting one of them…) in and the plyr package.

提交回复
热议问题