我有一个包含一些值的数据框。现在,我想仅在每一行中保留最大值,并将0赋给其余列,如下所示:
df <- data_frame(a= c(1,2,3,4,5),b= c(2,5,3,9,7),c= c(40,6,2,1,7))
df$rowmax <- apply(df,1,max)
#
a b c rowmax
<dbl> <dbl> <dbl> <dbl>
1 2 40 40
2 5 6 6
3 3 2 3
4 9 1 9
5 7 7 7
#ideal out put
a b c rowmax
0 0 40 40
0 0 6 6
3 3 0 3
0 9 0 9
0 7 7 7
有人可以帮我吗?谢谢 ; )
使用pmax
明智的方法来使行更明智max
,然后选择要插入的列,mutate_at
并且replace
每列中的值都不等于0
library(dplyr)
library(purrr)
df %>%
mutate(rowmax = reduce(., pmax)) %>%
#or as @tmfmnk mentioned in the comments
# mutate(rowmax = exec(pmax, !!!.)) %>%
mutate_at(vars(a:c), ~ replace(., .!= rowmax, 0))
#Or do a multiplication
#mutate_at(vars(a:c), ~. * (.== rowmax))
另外,如果我们不需要该rowmax
列,则可以base R
选择
df * (df == do.call(pmax, df))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句