0

I ran the below code:

for (i in 1:12) {
  if (i %% 2 ==1) print(i)
  ifelse (i=3,"three",i)}

I want the output to reflect the word three whenever 3 comes in the output.

I get the below error:

Error in ifelse(i = 3, "three", 1:12) : unused argument (i = 3)

3 Answers3

1

Two issues: As noted elsewhere "=" sets the value of i to 3, "==" tests whether i is equal to 3. The second is that this statement never really DOES anything because the result is not saved or printed.

Usually you would do something like:

i <- ifelse(i==3,"three",i)

which sets the values of i, although that has the issue that you've now converted vector i from being numeric to being a string, so something like:

mystring <- ifelse(i==3,"three",as.character(i))

might be better.

J Porter
  • 51
  • 3
0

If I understand you correctly, you want to print all the odd numbers but when it is 3, you want it in words. Your code should look like:

for (i in 1:12) {
  if (i %% 2 == 1) {
    if (i == 3) {
      print("Three")
    }
    else print(i)
  }
}


#Output
#[1] 1
#[1] "Three"
#[1] 5
#[1] 7
#[1] 9
#[1] 11
SmitM
  • 1,366
  • 1
  • 8
  • 14
0

couple items in your code;

i = 3

A single equal sign, "=", means assignment (the same as "<-"). Whereas you are looking for equality "=="

if (i %% 2 == 1)

print(i)

Not sure what the above code is doing. I think you can comment that code out.

You also need the print() added.

for (i in 1:12) {
  ifelse (i == 3, print("three"), print(i))
}
M.Viking
  • 5,067
  • 4
  • 17
  • 33