基于多个条件添加新列

时间:2020-06-01 19:19:18

标签: r if-statement dplyr

我有一个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)

1 个答案:

答案 0 :(得分:2)

我们可以使用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)