Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print values in a list that are greater than a certain number along with the row name in R?

Tags:

loops

r

I am painfully new to R. I have a list of data, and I wrote a loop to find which values are greater than a certain number:

for (i in listname){
    if(i > x)
    print(i)
}

I would like for the printed values to also include the row name... how would I go about doing that? Thanks for your patience.

like image 437
hmg Avatar asked Sep 05 '25 03:09

hmg


1 Answers

Strangely, when the item itself is the iterator, the name is lost. If you instead iterate over the number of the item, print works as expected:

for (i in 1:length(listname)){
    if (listname[i] > x){
        print(listname[i]) # value with name
    } 
}

Once you've learned more about R, you will probably want to do this in a "vectorized" way, instead of using a loop:

idx <- which(listname > x) # row numbers
listname[idx]              # values with names

or with logical subsetting

gt_x<-  listname > x       # TRUE or FALSE
listname[gt_x]             # values with names

Example: Try this with

listname <- 1:10
names(listname) <- letters[1:10]
x <- 4
idx <- which(listname > x) # row numbers
listname[idx]              # values with names
# e  f  g  h  i  j 
# 5  6  7  8  9 10
like image 194
Frank Avatar answered Sep 08 '25 00:09

Frank