简体   繁体   English

根据其他三列中的值添加一列

[英]add a column based on values in three other columns

I have a data frame ('ju') that has three columns and 230 rows.我有一个包含三列和 230 行的数据框('ju')。 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.我想添加第四列,其中将包含该对中的第二个 object,如下所示。

在此处输入图像描述

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.我编写了一个代码来识别第四列(失败者)的值,但是当我运行它时它没有给我任何 output。

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谢谢

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):关于 New Column 问题,一个可能的解决方案(在此处使用 for 循环不是最佳选择——请参阅@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]
  }
}

This will do it without a for loop:这将在没有for循环的情况下完成:

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

with tidyverse:与 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM