rdata:在数据框的行上应用dist()

时间:2015-05-18 01:36:30

标签: r rdata

我可以这样做:

data <- read.csv("data.csv")
p1 <- subset(data, player_name == 'Player1')
p2 <- subset(data, player_name == 'Player2')

dist(rbind(p1[,c("gp","points")], p2[,c("gp","chances_for","chances_for_help")]))

我得到了距离。但是data中有超过1000行,我希望每一行都有基于GP和点数的十个最相似的记录,但我无法弄明白。

类似的东西:

apply(data, 1, function(p) {
    dist(rbind(p, data))
})

但显然这不起作用。这里有快速解决方法吗?

示例数据:

player_name,gp,points
Player 1,82,95
Player 2,80,88
Player 3,81,84
Player 4,82,90
Player 5,82,77

1 个答案:

答案 0 :(得分:0)

@thelatemail基本上给了你完整的答案。因此,进一步研究他的方法,您可以通过以下方式扩展它(我使用dplyr库)。

首先创建一个行ID:

library(dplyr)
data <- data %>% mutate(rowid = row_number())

...并将距离数据转换为数据框:

dist_data <- as.data.frame(t(apply(out, 1, function(x) colnames(out)[order(x)[2:4]])))
dist_data <- dist_data %>% mutate(rowid = row_number())

然后您就可以加入rowid

data <- data %>% left_join(dist_data, by="rowid")

要添加播放器的名称,您只需创建某种播放器索引数据框,并使用相同的想法进行更多连接:

data$V1 <- as.numeric(data$V1)
data$V2 <- as.numeric(data$V2)
data$V3 <- as.numeric(data$V3)

# now we have to remap the V1, V2, V3 to the player_name and id's..
# we can do this by create a name dataset with the indexes...
name_index <- dplyr::select(data, player_name, rowid)

data %>% 
  left_join(rename(name_index, closest_name1=player_name, V1=rowid)) %>% 
  left_join(rename(name_index, closest_name2=player_name, V2=rowid)) %>%
  left_join(rename(name_index, closest_name3=player_name, V3=rowid)) %>%
  dplyr::select(-V1, -V2, -V3)

输出:

  player_name gp points rowid closest_name1 closest_name2 closest_name3
1    Player 1 82     95     1      Player 3      Player 2      Player 2
2    Player 2 80     88     2      Player 3      Player 3      Player 1
3    Player 3 81     84     3      Player 1      Player 4      Player 4
4    Player 4 82     90     4      Player 1      Player 1      Player 2
5    Player 5 82     77     5      Player 2      Player 2      Player 3