首页 > 解决方案 > 根据两列中的信息向我的数据框添加一列

问题描述

我想根据数据框两列中的信息向我的数据框添加一列。

在我的示例数据框中,我有一个样本的两行条目,它们是第 3 行和第 4 行。我想编写一个新列“main”并在每行填充“1”的代码,该行具有唯一的标签号。对于具有重复标签编号的行,我需要权重最高的行在 main 中为“1”,所有其他行都用“0”填充。

df
       sp    weight   tag
1   green        70     1
2  yellow        63     2
3     red        41     3
4     red        25     3
5     red         9     3
df with "main" column added
       sp    weight   tag  main
1   green        70     1     1
2  yellow        63     2     1
3     red        41     3     1
4     red        25     3     0
5     red         9     3     0

这是我到目前为止所拥有的:

df$is.uniq <- duplicated(df$tag) | duplicated(df$tag), fromLast = TRUE) 
df$main <- ifelse(is.uniq==TRUE, "1", ifelse(is.uniq==FALSE, "0", NA  )) 

我知道我需要更改第二个 ifelse 语句以引用权重列,并为最大权重填写 1,为其他所有内容填写 0,但我还没有弄清楚如何做到这一点。

标签: rif-statementunique

解决方案


我们可以按操作创建一个组,并使用max“权重”在逻辑条件下创建二进制文件

library(dplyr)
df %>% 
     group_by(sp) %>% 
      mutate(main = +(weight == max(weight)))

-输出

# A tibble: 5 x 4
# Groups:   sp [3]
#  sp     weight   tag  main
#  <chr>   <int> <int> <int>
#1 green      70     1     1
#2 yellow     63     2     1
#3 red        41     3     1
#4 red        25     3     0
#5 red         9     3     0

或者在base R一个选项中,首先order按“权重”按降序排列数据,然后应用duplicated

dfnew <- df[order(df$sp, -df$weight),]
dfnew$main <- +(!duplicated(dfnew$sp))

数据

df <- structure(list(sp = c("green", "yellow", "red", "red", "red"), 
    weight = c(70L, 63L, 41L, 25L, 9L), tag = c(1L, 2L, 3L, 3L, 
    3L)), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5"))

推荐阅读