【发布时间】:2020-09-07 12:52:42
【问题描述】:
目标:发现钻石组合中的钻石相似之处。此外,为每个钻石名称创建一行(通过状态集自动填充),其中包括每个钻石的相似性列。
工作:下面,我创建了一个函数,它使用 dplyr 通过将钻石的名称输入到函数中并过滤相似属性来发现钻石的相似性。
问题:我的函数有效,但一次只能处理一个钻石名称。我被困在如何在整个名称列表中重申我的功能。理想情况下,此迭代将返回每个唯一钻石名称及其相似属性的数据框。我尝试编写第二个函数,该函数使用 for 循环迭代名称列表,但无济于事。任何建议将不胜感激。
library(tidyverse)
diamonds <- diamonds[1:50,]
# I wanted to give each diamond a unique name, so I am using the states set to populate names.
diamonds$name <- state.name
diamonds
f_comp <- function(df = diamonds, name_insert, name_c = name, carat_c = carat, depth_c = depth, price_c = price){
name_c <- enquo(name_c)
carat_c <- enquo(carat_c)
depth_c <- enquo(depth_c)
price_c <- enquo(price_c)
#filter by specifc diamond name)
n <- df %>%
filter(name_insert == !! name_c)
#filtering by carat size, then measuring distance with mutate
prox <- df %>%
filter(!! carat_c <= n$carat +.04 & !! carat_c >= n$carat -.04) %>%
mutate(scores = abs(!! depth_c - n$depth) + abs(!! price_c - n$price)) %>%
arrange(scores)
#return avg scores of top 3 (ascending)
prox1 <- prox[1:3,]
prox1 <- prox1 %>%
mutate(avg_score = (mean(scores)))
#format
prox1 <- prox1 %>%
select(name, avg_score) %>%
mutate(nm1 = name[2], nm2 = name[3])
#Return one row w/ avg score
prox_db <- prox1[1,]
}
test_alaska <- f_comp(name_insert = "Alaska")
*#Everything works until I try to add the second function that reiterates the name column*
func2 <- function(d) {
storage <- data.frame()
for(i in d) {
storage[i] <- f_comp(name_insert = i)
storage
}
}
test_5 <- func2(d = diamonds$name)
【问题讨论】: