Vasile
Vasile

Reputation: 1017

add a column based on values in three other columns

I have a data frame ('ju') that has three columns and 230 rows. The first two columns represent a pair of objects. The third column includes one of those objects. I'd like to add the fourth column which will contain the second object from that pair, as shown below.

enter image description here

I wrote a code to identify the value for the forth column (loser), but it does not give me any output when I run it.

for (i in 1:230) {
  if (ju$winner[i]==ju$letter2[i]) {
    paste(ju$letter1[i])
  } else {
    paste (ju$letter2[i])
  }
}

I can not see what is wrong with the code. Also I would appreciate if you can suggest how I could create this fourth column directly into my data frame, instead of creating a separate vector and then adding it to the data frame. Thanks

Upvotes: 0

Views: 58

Answers (3)

uceslc0
uceslc0

Reputation: 81

If you want to print to console, you'll need to add:

cat(ju$letter1[i])

or

print(ju$letter1[i])

Regarding the New Column question, a possible solution (sub-optimal to use a for loop here -- See suggestion from @lab_rat_kid):

ju$NewColumn = NA
for (i in 1:230) {
  if (ju$winner[i]==ju$letter2[i]) {
    ju$NewColumn[i] <- ju$letter1[i]
  } else {
    ju$NewColumn[i] <- ju$letter2[i]
  }
}

Upvotes: 1

abreums
abreums

Reputation: 196

with tidyverse:

dt <- tibble(l1 = c("a", "c", "t", "r"),
             l2 = c("c", "b", "j", "k"),
             winner = c("a", "b", "j", "k"))
dt <- dt %>% 
  mutate(looser = if_else(winner == l1, l2, l1))
(dt)

Upvotes: 0

Elk
Elk

Reputation: 532

This will do it without a for loop:

ju$loser <- ifelse(ju$winner %in% ju$letter1, ju$letter2, ju$letter1)

Gives:

> ju
  letter1 letter2 winner loser
1       a       c      a     c
2       c       b      b     c
3       t       j      j     t
4       r       k      k     r

Upvotes: 1

Related Questions