How do I print values in a list that are greater than a certain number along with the row name in R?
17,577
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
Related videos on Youtube
Author by
hmg
Updated on June 04, 2022Comments
-
hmg almost 2 years
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.
-
hmg over 10 yearsThanks so much for this. It makes sense and I can see why it would work over what I did (all three ways), but when I try any of the methods with my data, I'm still not getting the names. I created my list by binding vectors together, so there are 3 columns and thousands of rows. If I do the loop you suggested for one of the vectors, it prints out the names. Is there a way to code it so I can apply it to the entire list and still get the names?
-
Frank over 10 yearsNo problem. You might want to make that a separate question. I would do something like
myfun <- function(z) z[which(z > x)]; lapply(DF,myfun)
, assuming you have them in a data.frame... if notDF <- data.frame(your_mat)
will create it.