r - 在数据帧的每一行上运行函数,将结果存储在新列中,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)
}
解决方案
尝试:
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]))
推荐阅读
- flutter - gridview Flutter中Listtile/card的背景图片
- assembly - MIPS中括号的作用是什么?
- sql - 查询新列和指数
- machine-learning - 多标签文本分类问题的核心学习
- python - 在 all() 函数中,“for”如何评估为真或假?
- c++ - 给定 64 位进程的 PID,如何从 32 位进程获取其可执行路径?
- sass - Nextjs如何添加antd
- android - npx react-native start 和 npx react-native run-android 太慢了
- python - 在 Windows 上安装 Turi Create 时出错
- node.js - 如何通过公共 IP 地址访问我的 node.js 服务器?