首页 > 解决方案 > 在数据帧的每一行上运行函数,将结果存储在新列中,R

问题描述

我想在数据帧的每一行上运行函数 sum_differences 并将结果存储在新列“di_Flex”中。a 是 column Company ID,每个 Company ID 存在多行。b 是列max_di_Flex。谁能帮我解决for循环?谢谢!

data <- df <- data.frame(structure(list(`Company ID` = c(0, 0, 0, 0, 0, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6), Action = c(5, 5, 2, 4, 5, 5, 3, 1, 5, 7, 2, 4, 2, 6, 2, 3, 1, 4, 1, 5), Flexibility_Thinking = c(7, 2, 5, 1, 6, 5, 7, 7, 4, 7, 5, 2, 3, 3, 3, 3, 4, 3, 6, 6), max_di_Flex = c(12.8, 12.8, 12.8, 12.8, 12.8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16))))
data <- data %>% group_by(`Company ID`) %>% filter(length(`Company ID`) > 1)
data <- data %>% drop_na(`Flexibility_Thinking`)

sum_differences <- function(a,b) {
  a <- unique(a)
  new_list <- c()

  for (i in a) {
    for (j in a) {
      if(i != j) {
        new_list <- c(new_list, abs(i-j))
      }
    }
  }
  outcome <- round((sum(new_list) / length(a)), 2)
  percent <- outcome/b
  return(percent)
}

标签: rdataframefunction

解决方案


尝试:

data$di_Flex <- apply(data, 1, function(x) sum_differences(x[1], x[3]))

或者:

data$di_Flex <- apply(as.data.frame(data), 1, function(x) sum_differences(x[1], x[3]))

推荐阅读