1

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
  • Should have been names(B_list)[i]. You tried to get the name of 1. It doesn't have a name, it's just a number. You should have gotten an error and then searched SO with selected parts of the error message. Commented Jul 19, 2022 at 2:20

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Incredible! Thanks. Loops are new to me so very grateful for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.