我正在使用的数据框是
> 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,那么我需要最大值 m(75,M1)。对于 Jack,M1 是 55,所以我应该得到 max(75,55),即 75。我认为它给了我整个 M1 列的最大值。如何避免这种情况?
期望的输出
Name M1 Final
1 Joy 10 60
2 Jane 40 60
3 Jack 55 75
4 Jad 90 90
最佳答案
您还可以使用 pmax
代替 max
:
ifelse(df$M1 <= 50, 60, pmax(75, df$M1))
从帮助文件中,pmax
需要
one or more vectors (or matrices) as arguments and return(s) a single vector giving the ‘parallel’ maxima ... of the vectors. The first element of the result is the maximum ... of the first elements of all the arguments, the second element of the result is the maximum ... of the second elements of all the arguments and so on.
因此,ifelse
的第三个参数(“else”值)是成对最大值 75(根据需要回收多次)和 df$M1 的值。
关于r - 在数据框中使用 Ifelse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309423/