user13267770
user13267770

Reputation:

grouping values and bringing values into character string

This is an example we can work with:

df <- tibble(a = c("aaa", "aaa", "aaa", "bbb", "bbb", "bbb"), 
             b = c(1,2,3,1,2,3), c = c(5,10,15,100,95,90))
df
# A tibble: 6 x 3
  a         b     c
  <chr> <dbl> <dbl>
1 aaa       1     5
2 aaa       2    10
3 aaa       3    15
4 bbb       1   100
5 bbb       2    95
6 bbb       3    90

I want to group the values in column a and combine column b and c to a single string. The final result should look exactly like this:

# A tibble: 2 x 2
  a         result
  <chr>     <chr>
1 aaa       {"1":5,"2":10,"3":15}
2 bbb       {"1":100,"2":95,"3":90}

and reads like this: aaa has 5 times 1, 10 times 2 and 15 times 3 etc.

I dont even know where to start honestly. Maybe with some dplyr::group_by and paste? I am glad for any hint.

Upvotes: 0

Views: 66

Answers (1)

jay.sf
jay.sf

Reputation: 73782

Using the entire artillery paste, toString, sprintf.

b <- by(df[-1], df$a, function(x) 
  sprintf("{%s}", toString(Reduce(paste0, c(x, "'", "':")[c(3, 1, 4, 2)]))))
data.frame(a=unique(df$a), result=do.call(rbind, as.list(b)), row.names=NULL)
#     a                    result
# 1 aaa   {'1':5, '2':10, '3':15}
# 2 bbb {'1':100, '2':95, '3':90}

Note: You may also use '"' quotes, will get escaped in display though.

Upvotes: 0

Related Questions