在R中,如何确保 Dataframe 中某些列的值总是递减?

qfe3c7zg  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(103)

你能告诉我我的代码出了什么问题吗?
我有这样的数据,我需要检查在我的数据框中跨列yr1,yr2和yr3的值是否都在不断减少(或相等),并标记那些不是的(例如product 1)。

check <- data.frame(type = c("product 1","product 2","product 3"), yr1 = c(10, 5, 0), yr2 = c(15, 3, 0), yr3 = c(10, 2, 0), yr4 = c(7, 2, 0), yr5 = c(1, 1, 0))


check$TLS_error<- ""
for (i in 1:nrow(check)){
#  starts with base_rate ends with second to least year
for(j in 2:ncol(check)-2){
  if(check[i,j]<check[i,j+1]){
  check$TLS_error[i]<-1
    }
   next
     }
   }

check %>%
filter(check$TLS_error==1)```
up9lanfz

up9lanfz1#

以下是使用自定义函数和apply的建议:

# function that checks if values in a row are decreasing from left to right
my_func <- function(row) {
  all(diff(row) <= 0)
}

check$TLS_error <- as.integer(apply(check[-1], 1, my_func))
check
col1 yr1 yr2 yr3 TLS_error
1 product 1  10  15  10         0
2 product 2   5   3   2         1
3 product 3   0   0   1         0

相关问题