0

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.

Vlad
  • 3,058
  • 4
  • 25
  • 53
  • 1
    Have you tried this? https://stackoverflow.com/questions/14568662/paste-multiple-columns-together – Ronak Shah Jun 18 '18 at 12:25
  • `df %>% mutate(spark = spk_chr(values = c(X1, X2, X3), type = "bar", elementId = X1))`? – Axeman Jun 18 '18 at 12:30
  • @Axeman That did not work - it gave the same value for each row. Tried Vectorize(spk_chr) and this changed the elementId, however the values were incorrect for each row. – Vlad Jun 18 '18 at 12:40
  • I'm not really sure what your goal is here. How can you plot a bar for each row, with three separate elements in each row? Do you want to plot the sum? – Axeman Jun 18 '18 at 12:43
  • @RonakShah - with your suggestion I created a column of strings that concat each row of values. Then used strsplit in the values argument for spk_chr. This worked. Not sure if there is a more direct approach to avoid string intermediate stage. – Vlad Jun 18 '18 at 12:49

1 Answers1

1

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))
Vlad
  • 3,058
  • 4
  • 25
  • 53