![](/img/trans.png)
[英]R apply function to each row of dataframe, store result in new column of same dataframe
[英]run function on every row of dataframe, store result in new column, R
我想在數據幀的每一行上運行函數 sum_differences 並將結果存儲在新列“di_Flex”中。 a 是列Company ID
,b 是列max_di_Flex
。 誰能幫我解決 for 循環? 謝謝!
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 <- data.frame(structure(list(`Company ID` = c(0, 0, 0, 0, 0, 1, 2, 3, 4, 5,
5, 5, 6, 6, 6, 6, 6, 6, 6, 6), Flexibility_Thinking = c(7, 2,
5, 1, 6, 3, 6, 6, 7, 5, 7, 7, 4, 7, 5, 2, 3, 3, 3, 3), max_di_Flex = c(12.8,
12.8, 12.8, 12.8, 12.8, 0, 0, 0, 0, 8, 8, 8, 16, 16, 16, 16,
16, 16, 16, 16))))
嘗試:
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]))
使用map2_dbl
Tidyverse 解決方案(當您有一個接受 2 個輸入並返回一個數字的函數時):
df <- as.data.frame(data)
library(tidyverse)
df %>%
mutate(diFlex = map2_dbl(Company.ID, max_di_Flex, sum_differences))
#> Company.ID Flexibility_Thinking max_di_Flex diFlex
#> 1 0 7 12.8 0
#> 2 0 2 12.8 0
#> 3 0 5 12.8 0
#> 4 0 1 12.8 0
#> 5 0 6 12.8 0
#> 6 1 3 0.0 NaN
#> 7 2 6 0.0 NaN
#> 8 3 6 0.0 NaN
#> 9 4 7 0.0 NaN
#> 10 5 5 8.0 0
#> 11 5 7 8.0 0
#> 12 5 7 8.0 0
#> 13 6 4 16.0 0
#> 14 6 7 16.0 0
#> 15 6 5 16.0 0
#> 16 6 2 16.0 0
#> 17 6 3 16.0 0
#> 18 6 3 16.0 0
#> 19 6 3 16.0 0
#> 20 6 3 16.0 0
從我在另一個答案上看到的評論中,我意識到該函數是采用向量而不是單個值。 這意味着您不需要循環,而應該直接在向量上調用該函數:
df %>%
mutate(diFlex = sum_differences(df$Company.ID, df$max_di_Flex))
#> Company.ID Flexibility_Thinking max_di_Flex diFlex
#> 1 0 7 12.8 1.25
#> 2 0 2 12.8 1.25
#> 3 0 5 12.8 1.25
#> 4 0 1 12.8 1.25
#> 5 0 6 12.8 1.25
#> 6 1 3 0.0 Inf
#> 7 2 6 0.0 Inf
#> 8 3 6 0.0 Inf
#> 9 4 7 0.0 Inf
#> 10 5 5 8.0 2.00
#> 11 5 7 8.0 2.00
#> 12 5 7 8.0 2.00
#> 13 6 4 16.0 1.00
#> 14 6 7 16.0 1.00
#> 15 6 5 16.0 1.00
#> 16 6 2 16.0 1.00
#> 17 6 3 16.0 1.00
#> 18 6 3 16.0 1.00
#> 19 6 3 16.0 1.00
#> 20 6 3 16.0 1.00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.