我需要在数据集中的每一行中添加指纹
我知道如何在r中为每行添加哈希,如下所示:
data.frame(iris,hash=apply(iris,1,digest))
我正在学习使用dplyr
,因为数据集变得越来越大,我需要将它们存储在SQL Server中,我尝试了以下类似的东西,但是Hash不起作用,所有行都会给出相同的哈希:
iris %>%
rowwise() %>%
mutate(hash=digest(.))
使用dplyr的排名散列的任何线索?谢谢!
我们可以使用do
res <- iris %>%
rowwise() %>%
do(data.frame(., hash = digest(.)))
head(res, 3)
# A tibble: 3 x 6
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species hash
# <dbl> <dbl> <dbl> <dbl> <fctr> <chr>
#1 5.1 3.5 1.4 0.2 setosa e261621c90a9887a85d70aa460127c78
#2 4.9 3.0 1.4 0.2 setosa 7bf67322858048d82e19adb6399ef7a4
#3 4.7 3.2 1.3 0.2 setosa c20f3ee03573aed5929940a29e07a8bb
请注意,在apply
过程中,所有列都转换为单个类,因为apply
转换为matrix
,并且矩阵只能容纳一个类。将有警告将factor
转换为character
类
由于do
已被取代,此选项现在可能更好:
library(digest)
library(tidyverse)
# Create a tibble for practice
df <- tibble(x = rep(c(1,2), each=2), y = c(1,1,3,4), z = c(1,1,6,4))
# Note that row 1 and 2 are equal.
# This will generate a sha1 over specific columns (column z is excluded)
df %>% rowwise() %>% mutate(m = sha1( c(x, y ) ))
# This will generate over all columns,
# then convert the hash to integer
# (better for joining or other data operations later)
df %>%
rowwise() %>%
mutate(sha =
digest2int( # generates a new integer hash
sha1( c_across(everything() ) ) # across all columns
)
)
将所有内容转换为角色并将其粘贴在一起以使用一个哈希功能调用可能是一个更好的选择。您可以使用unite
:
df %>% rowwise() %>%
unite(allCols, everything(), sep = "", remove = FALSE) %>%
mutate(hash = digest2int(allCols)) %>%
select(-allCols)