Can I extract a variable name from a vector using a for loop?

Viewed 39

I am practicing loops and trying to figure out how to print ___ is a good friend if their number is odd (through an assigned number in a vector) - why won't it print the names of the people in the vector who are coded as odd numbers?

B_list <- c(Bob=1, Bill=2, Buddy=3) # create character vector

phrase <- "is a good friend"

for (i in B_list){
    if((i %% 2) != 0)
        print(paste(names(i),phrase))
}

Output:

[1] " is a good friend"
[1] " is a good friend"
1 Answers

names(listName[i]) should be used to get the name of the item in the list, and listName[[i]] should be used to get the value of the item in the list.

B_list <- c(Bob=1, Bill=2, Buddy=3)

phrase <- "is a good friend"

for (i in B_list) {
    if((i %% 2) != 0) {
        print(paste(names(B_list[i]), phrase))
        
        print(paste("Name: ", names(B_list[i])))
        print(paste("Value: ", B_list[[i]]))
    }
}

The output:

[1] "Bob is a good friend"
[1] "Name:  Bob"
[1] "Value:  1"
[1] "Buddy is a good friend"
[1] "Name:  Buddy"
[1] "Value:  3"
Related