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