user27815
user27815

Reputation: 4797

Collapsing one col by another in R

I have a dataframe where the top looks like:

>head(transposed_label,20)
      val index
 [1,] "0" "1"  
 [2,] "1" "1"  
 [3,] "0" "1"  
 [4,] "0" "2"  
 [5,] "1" "2"  
 [6,] "0" "2"  
 [7,] "1" "3"  
 [8,] "0" "3"  
 [9,] "0" "3"  
[10,] "0" "4"  
[11,] "1" "4"  
[12,] "0" "4"  
[13,] "0" "5"  
[14,] "0" "5"  
[15,] "1" "5"  
[16,] "0" "6"  
[17,] "1" "6"  
[18,] "0" "6"  
[19,] "0" "7"  
[20,] "0" "7"

I want to collapse the values in "val" by "index"

I have tried:

>library(dplyr)

>new <- as.data.frame(transposed_label) %>% group_by(as.numeric(index))
%>% summarise(val = paste(val, collapse =","))

But this gives me:

head(new,10)
# A tibble: 10 x 2
      as.numeric(index) val  
                <dbl> <chr>
1                   1 0,1,0
2                   2 1,0,0
3                   3 0,1,0
4                   4 0,1,0
5                   5 1,0,0
6                   6 0,1,0
7                   7 0,1,0
8                   8 0,0,1
9                   9 0,0,1
10                  10 1,0,0

When I would expect something like:

1 0,1,0
2 0,1,0
3 1,0,0
4 0,1,0
5 0,0,1

etc

What have I done wrong?

Upvotes: 1

Views: 34

Answers (1)

akrun
akrun

Reputation: 887118

It looks like the columns were factor with as.data.frame and the values got were the integer coersion. So, if we use the stringsAsFactors = FALSE, should solve the issue

as.data.frame(transposed_label, stringsAsFactors = FALSE) 

Upvotes: 2

Related Questions