【问题标题】:Adding new column based on multiple conditio根据多个条件添加新列
【发布时间】:2020-06-01 19:19:18
【问题描述】:

我有一个data,看起来像这样:

< Id <- c(A,B,C,D,E)
< Father <- c(2,1,5,4,2)
< Mother <- c(1,3,3,5,1)

我想要的是根据父亲或母亲的更高价值添加一个新列parent。基本上:

< Id <- c(A,B,C,D,E)
< Father <- c(2,1,5,4,2)
< Mother <- c(1,3,3,5,1)
< Parent <- c(2,3,5,5,2)

【问题讨论】:

    标签: r if-statement dplyr


    【解决方案1】:

    我们可以使用pmax 来获取多个列的元素max

    library(dplyr)
    df1 %>%
        mutate(Parent = pmax(Father, Mother))
    

    或在base R

    df1$Parent <- with(df1, pmax(Father, Mother))
    

    或者ifelse的另一个选项

    df1$Parent <- with(df1, ifelse(Father > Mother, Father, Mother))
    

    数据

    df1 <- data.frame(Id, Father, Mother)
    

    【讨论】:

    • 完美。谢谢@akrun
    猜你喜欢
    • 2019-07-21
    • 2022-11-25
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2019-08-29
    • 2018-09-10
    相关资源
    最近更新 更多