[英]How do I print values in a list that are greater than a certain number along with the row name in R?
我是R的新手,我很痛苦。我有一個數據列表,我寫了一個循環來查找哪些值大於某個數字:
for (i in listname){
if(i > x)
print(i)
}
我希望打印的值還包括行名...我該怎么做呢? 謝謝你的耐心。
奇怪的是,當項目本身是迭代器時,名稱就會丟失。 如果改為遍歷項目編號,則print
將按預期進行:
for (i in 1:length(listname)){
if (listname[i] > x){
print(listname[i]) # value with name
}
}
一旦了解了有關R的更多信息,您可能會希望以“向量化”的方式進行操作,而不是使用循環:
idx <- which(listname > x) # row numbers
listname[idx] # values with names
或具有邏輯子集
gt_x<- listname > x # TRUE or FALSE
listname[gt_x] # values with names
示例:嘗試使用
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.