tafelplankje
tafelplankje

Reputation: 593

looking for the inverse of splitstackshape ::cSplit_e()

I am looking to do the inverse of this:

library(splitstackshape)
temp <- head(concat.test) [-3:-4]
cSplit_e(temp, "Likes", fill = 0)[-2]

so return this:

enter image description here back to: enter image description here

Upvotes: 0

Views: 67

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389175

Another way would be to get data in long format and concatenate the columns which has 1 in them for each name.

Using data from @r2evans -

library(dplyr)
library(tidyr)

dat %>%
  pivot_longer(cols = -name, names_to = 'col') %>%
  mutate(col = sub('V', '', col)) %>%
  group_by(name) %>%
  summarise(Likes = toString(col[value == 1]))

#  name  Likes  
#  <chr> <chr>  
#1 A     3, 7   
#2 B     3, 4, 5
#3 C     3, 5   
#4 D     4, 5   
#5 E     2, 3, 5

Upvotes: 1

r2evans
r2evans

Reputation: 160677

set.seed(42)
dat <- data.table(name = LETTERS[1:5])[, c(.SD, replicate(6, sample(0:1, size=5, replace=TRUE), simplify=FALSE))]
dat
#      name    V2    V3    V4    V5    V6    V7
#    <char> <int> <int> <int> <int> <int> <int>
# 1:      A     0     1     0     0     0     1
# 2:      B     0     1     1     1     0     0
# 3:      C     0     1     0     1     0     0
# 4:      D     0     0     1     1     0     0
# 5:      E     1     1     0     1     0     0

dat[, .(name, Likes = apply(as.matrix(.SD[,-1]), 1, function(z) toString(which(z > 0))))]
#      name   Likes
#    <char>  <char>
# 1:      A    2, 6
# 2:      B 2, 3, 4
# 3:      C    2, 4
# 4:      D    3, 4
# 5:      E 1, 2, 4

Upvotes: 2

Related Questions