Home > front end >  How to use the digest library on a column in r
How to use the digest library on a column in r

Time:03-29

I get an error using this:

for (i in nrow(df$uuid)){df$uuid[[,i]] <- (digest(df$uuid[i,], algo=c("sha256")))}

Error in 1:nrow(s12$uuid) : argument of length 0

CodePudding user response:

A vector doesn't have an nrow value, only a length value:

x <- 1:10
nrow(x)
#> NULL

This includes vectors housed in data frames:

df <- data.frame(x = 1:10)
nrow(df$x)
#> NULL

Whereas, the data frame itself has an nrow (the number of rows) and a length (the number of columns):

nrow(df)
#> [1] 10
length(df)
#> [1] 1

You need to be careful when iterating that you are iterating along the correct "dimension" of the correct entity. In your case this means you should either give the for loop the nrow of your data frame or the length of one of its vectors (both will be the same), but not the nrow of one of its vectors, since that will be NULL.

It's not clear what len does in your example - is that a function you have pre-defined? Is it just a synonym for nrow?

The structure of your data isn't shown in your question, so let's make a really simple example. We will have a uuid column for "data" and create an empty column for the hash.

df <- data.frame(uuid = c("hello", "world"))
df$hash <- character(nrow(df))

To populate the hash column, we do:

for(i in 1:nrow(df)) df$hash[i] <- digest::digest(df$uuid[i], algo = "sha256")

Which results in:

#>   uuid                                                              hash
#> 1 hello 5d3c36bc8d42c8b679ba1ef4ef3c2bf7674fc42ae33a474b9ac1a032a24b9b1d
#> 2 world c2269227fa81bc9731bedddfe41594c00e3be9327e33339053ebc395adb4fa76
  • Related