在数据帧中使用Ifelse [英] Using Ifelse in a dataframe
本文介绍了在数据帧中使用Ifelse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的数据框是
> df <- data.frame(Name=c("Joy","Jane","Jack","Jad"),M1=c(10,40,55,90))
> df
Name M1
1 Joy 10
2 Jane 40
3 Jack 55
4 Jad 90
> df$Final <- ifelse(df$M1<=50,60,max(75,df$M1))
> df
Name M1 Final
1 Joy 10 60
2 Jane 40 60
3 Jack 55 90
4 Jad 90 90
如果M1值小于或等于50,那么我需要60作为我的最终值,而如果M1值大于50,那么我需要最大值(75,M1)。在杰克的情况下,M1是55,所以我应该得到最大值(75,55),这是75.我认为这是给我最大的整个M1列。如何避免这种情况?
If the M1 value is less than or equal to 50 then I need 60 as my final value, while if the M1 value is greater than 50 then I need the maximumm(75,M1). In the case of Jack, M1 is 55, so I should get the max(75,55) which is 75. I think it is giving me the max of entire M1 column. How to avoid this?
期望的输出
Name M1 Final
1 Joy 10 60
2 Jane 40 60
3 Jack 55 75
4 Jad 90 90
推荐答案
如何:
ifelse(df$M1<=50,60,ifelse(df$M1>75,df$M1,75))
这篇关于在数据帧中使用Ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文