【问题标题】:Convert data.frame into a row with the specific sorting of numeric and character data?将 data.frame 转换为具有数字和字符数据特定排序的行?
【发布时间】:2019-12-13 18:37:57
【问题描述】:

简介:在 R 中工作时,我经常需要从 data.frames 列表中重新组织信息以创建汇总表。在此示例中,我从单个 data.frame 开始,并展示了将关键信息从 data.frame 转换为单行的函数。考虑到我想要的输出需要对数字和字符数据的混合进行排序,我不禁想知道是否有更简单的技术来做这种事情。

我的问题:谁能提供建议,或者更好的解决方案,以更简单的技术将这样的 data.frames 转换为行,同时尊重数据的特定排序?

#sample data
input_df <- data.frame(M1 = c("Age", "Weight", "Speed", "Range"),
  dogs = c(100, 120, 85, 105),
  cats = c(115, 89, 80, 111),
  birds = c(100, 90, 100, 104))

# desired summary row
desired_row <- data.frame(Model = "M1",
  dogs = "Weight (120)",
  cats = "Age (115), Range (111)",
  birds = "Range (104)",
  stringsAsFactors = F)
desired_row$Model <- factor(desired_row$Model)

# my function

  makeRow <- function(dat1) {

    # get model name
    mod <- data.frame(Model = names(dat1[1]))

    # make list of variables with model varible 
    d1 <- setNames(lapply(names(dat1)[-1], function(x) cbind(dat1[1], 
      dat1[x])), names(dat1)[-1])

    # create a sorted named vector, largest-to-smallest
    sorted_named_vec <- function(x) {
      sort(setNames(x[[2]], x[[1]]), decreasing = T)
    }
    d2 <- lapply(d1, sorted_named_vec)

    # implement a criterion to report only top indexes
    keep_tops <- function(x) {
      ifelse(x == max(x) | x >= 110 | (x > 102) & ((x - 
          100)/(max(x) - 100) > 0.33), x, "")
    }
    d3 <- lapply(d2, keep_tops)

    # remove blank character elements
    remove_blank_elements <- function(x) {
      x[nchar(x) > 0]
    }
    d4 <- lapply(d3, remove_blank_elements)

    # collapse variable name with top values and add parenthesis
    collapse_to_string <- function(x) {
      paste0(names(x), " (", x, "),", collapse = " ")
    }
    d5 <- lapply(d4, collapse_to_string)

    # remove the last comma
    remove_last_comma <- function(x) {
      gsub("\\,$", "", x)
    }
    d6 <- lapply(d5, remove_last_comma)

    # consturct a row from the list
    row <- cbind(mod, as.data.frame(d6, stringsAsFactors = F))

    row
  }

  # call
  row_output <- makeRow(dat1 = input_df)
  row_output

  # check output to desired
  identical(desired_row, row_output)

【问题讨论】:

    标签: r


    【解决方案1】:

    不确定是否更高效,但代码略少,更直接地接近 imo。

      makeRow <- function(dat1) {
      #make data frame for row with model name
      d0 <- data.frame(mod = names(dat1)[1]) #col name changed later
    
    
      # implement a criterion to report only top indexes -> now return if true or false
      keep_tops <- function(x) {
        ifelse(x == max(x) | x >= 110 | (x > 102) & ((x - 100)/(max(x) - 100) > 0.33), T, F)
      }
      vals =c() #empty -> for values of each cols
      # make list of variables with model variables(dat1 cols)
      #use the columns of the df directly
      for(col in 2:ncol(dat1)){
      #make temp df with each and evaluate what row to keep in the same line
        df = dat1[keep_tops(dat1[,col])==1,c(1,col)]
        df[,2] = paste0("(",df[,2],")") #add the () around the numbers
        val = apply(as.data.frame(apply(df, 1, paste0, collapse=" ")), 2, paste0, collapse=", ") #collapse rows, then cols
        vals = c(vals, val) #add this variable values to the values' list
      }
      # bind the first col made earlier with these values
      row <- cbind(d0, as.data.frame(t(vals), stringsAsFactors = F))
      colnames(row) =  colnames(dat1) #rename the columns to match
    
      row
    }
    
    # call
    row_output <- makeRow(dat1 = input_df)
    # check output to desired
    identical(desired_row$birds, row_output$birds)
    

    使用您的“input_df”,相同()是 TRUE。

    【讨论】:

    • 很好的解决方案和有用的解释性 cmets。此外,虽然我的分析规模不需要速度优化,但您的函数似乎比我的快 50 倍。
    • 太酷了!我很高兴 :) 我没有检查速度(尽管我猜整个 df 列表的差异更明显)
    猜你喜欢
    • 2021-11-23
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    相关资源
    最近更新 更多