【问题标题】:add a column to my dataframe based on information in two columns根据两列中的信息向我的数据框添加一列
【发布时间】:2020-10-16 17:59:18
【问题描述】:

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

在我的示例数据框中,我有一个样本的两行条目,分别是第 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,但我还没有弄清楚如何做到这一点。

【问题讨论】:

    标签: r if-statement unique


    【解决方案1】:

    我们可以通过操作创建一个组,并使用“权重”的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"))
    

    【讨论】:

    • 谢谢! dplyr 解决方案帮助解决了我的问题。
    【解决方案2】:

    这行得通吗:

    > library(dplyr)
    > dat %>% left_join(dat %>% group_by(sp) %>% 
    +                     filter(weight == max(weight)) %>% 
    +                           mutate(main = 1) %>% select(X1, main), by = c('X1','sp')) %>% mutate(main = replace_na(main, 0))
    Adding missing grouping variables: `sp`
    # A tibble: 5 x 5
         X1 sp     weight   tag  main
      <dbl> <chr>   <dbl> <dbl> <dbl>
    1     1 green      70     1     1
    2     2 yellow     63     2     1
    3     3 red        41     3     1
    4     4 red        25     3     0
    5     5 red         9     3     0
    > 
    

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      相关资源
      最近更新 更多