简体   繁体   中英

Find all values in a list that are greater than a specified value

Using R I'm trying to count the number of elements in a list which are greater than a certain value, and store that number in a variable T .

However, I receive the following error

Error: (list) object cannot be coerced to type 'double'". After running the first section of the code I'm looking for the sum of all values > 3 each hist_lst

when I run the code below

A <- c(1, 1, 2,3,2,4,5,3,2,1,7)
value <- 5

# incrementations
out_lst <- lapply(A, function(x) x : 5)

hist_lst <- list()
max_len <- max(sapply(out_lst, function(x) length(x)))

for(l in 1:max_len) {
    hist_lst[[l]] <- sapply(out_lst, function(x) x[l])
    hist(hist_lst[[l]])
}

for(l in 1:length(hist_lst)) {
    for(i in 1:length(hist_lst[i])) {
        T[l] = sum(hist_lst[i] > 3)
    }
}

you need to put double brackets in:

 T[l] = sum(hist_lst[[i]] > 3)

but if I understand what you want you can replace the last double loop with

T=unlist(lapply(hist_lst,function(x) sum(x>3,na.rm=T)))

> T
[1] 3 4 6 6 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM