Vlad
Vlad

Reputation: 3764

R add column for sparkline with value from each row vector

Start with a dataframe

library(dplyr)
library(sparkline)
df <- data.frame(matrix(1:9, nrow = 3, ncol = 3))

   X1 X2 X3
1  1  4  7
2  2  5  8
3  3  6  9

Would like to add a column 'spark' for use with sparkline:

df <- df %>% mutate(spark = spk_chr(values = ?, type = "bar", elementId = X1))

So the question mark (?) would be replaced by a vector made up of each row of df.

For the first row, ? = c(1, 4, 7), the values from the first row, spark = spk(values = c(1, 4, 7)...)

I know how to extract a vector from any row, first row vector is unlist(df[1,]), but do not understand if this can be used in mutate.

Upvotes: 1

Views: 609

Answers (1)

Vlad
Vlad

Reputation: 3764

Used Ronak's suggestion to create intermediate column:

cols = names(df)
df$y <- apply(df[,cols], 1, paste, collapse = "-")

Then created vectorized spk_chr:

sparky <- Vectorize(sparkline::spk_chr)

To use in making the spark column:

df <- df %>% mutate(spark = sparky(strsplit(y, split="-"), type = "bar", elementId = X1))

Upvotes: 2

Related Questions