r - 在数据框中使用 Ifelse

标签 r if-statement dataframe

我正在使用的数据框是

> 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/

相关文章:

php - 从 PHP 运行 Rscript 时未加载库

R数据框-添加带有年份季度开始日期的新列

Python Pandas - 数据透视表输出意外 float

r - 如何在R包forestplot中添加第二条垂直线

r - knitr:以 pdf 和 png 格式保存图形,但在最终文档中使用 pdf 文件

php - 为什么我无法访问该数组中的第二个元素,while 循环问题

java - 使用 While 与 If 防止数组中出现重复的整数 ID 号

javascript - Jquery 滚动倾斜

python - 使用 groupby 和 cumcount (pandas) 计算每列的连续字符串

r - 如何使用 R 中的 caretEnsemble 包预测新数据集?