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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With