【问题标题】:R Data Frames - Assigning a Text Value Based on Adjacent Columns ValuesR数据框-根据相邻列值分配文本值
【发布时间】:2020-01-27 10:58:08
【问题描述】:

我对 R 很陌生,我正在尝试做一些我只能想象非常简单的事情,但我似乎无法让它发挥作用。

我正在尝试根据数据框中已填充的四分位数值添加一个新列,该列将显示:“第一四分位数”、“第二四分位数”等。我认为这将是一个简单的 if else 语句工作,但我下面的代码仅使用“第四四分位数”填充新列,当输出所基于的列中存在 NA 时使用“无值”。

我的代码是:

Quartile_Apply <- function(row) { 
  One_Y_return <- row[10]

  if (is.na(One_Y_return)) {
    return("No Value")
  }

    if (One_Y_return <= 25 & One_Y_return > 0) {
      return("First Quartile")
    } else if (One_Y_return <= 50 & One_Y_return > 25) {
      return("Second Quartile")
    } else if (One_Y_return <= 75 & One_Y_return >50) {
      return("Third Quartile" )
    } else {
      return("Fourth Quartile")
    }
  }

df_Fund_Fee_Data$`1Y_Perf_Quartile` <- apply(df_Fund_Fee_Data, 1, Quartile_Apply)

View(df_Fund_Fee_Data)

row[10] 部分旨在将 if 语句指向“1Y_Return_Percentile”列,四分位数将基于该列,即该列是第 10 列,然后应用于数据框中的所有行。

我觉得这不应该那么复杂,我可能会遗漏一些明显的东西,但我无法让它工作!我也尝试了一堆不同的代码改编,所以我只是附上了我目前的工作状态。

提前非常感谢, 哈利

【问题讨论】:

    标签: r dataframe if-statement


    【解决方案1】:

    我认为你应该使用cut/findInterval

    values <- paste(c("First", "Second", "Third", "Fourth"), "Quartile")
    
    df_Fund_Fee_Data$`1Y_Perf_Quartile` <- cut(df_Fund_Fee_Data$`1Y_Return_Percentile`, 
                                           seq(0, 100, 25), labels = values)
    

    或者

    df_Fund_Fee_Data$`1Y_Perf_Quartile` <- values[findInterval(
              df_Fund_Fee_Data$`1Y_Return_Percentile`, seq(0, 100, 25))]
    

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 2022-11-04
      • 2021-07-27
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多