shiva.n404
shiva.n404

Reputation: 478

Merging multiple rows by disticnt row value into a single column

Using R trying to merge raw matrix to result a matrix based on the value of the row value.

Ex:

from:

1  2
a1 10
a1 20
a1 40
a2 45
a2 50
a3 40
a4 45
a4 60

to:

10 20 40
45 50
40
45 60

Upvotes: 2

Views: 69

Answers (2)

989
989

Reputation: 12937

Or using aggregate:

aggregate(df$X2~df$X1, df, rbind)

  # df$X1      df$X2
# 1    a1 10, 20, 40
# 2    a2     45, 50
# 3    a3         40
# 4    a4     45, 60

DATA

df <- structure(list(X1 = structure(c(1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L
), .Label = c("a1", "a2", "a3", "a4"), class = "factor"), X2 = c(10L, 
20L, 40L, 45L, 50L, 40L, 45L, 60L)), .Names = c("X1", "X2"), class = 
"data.frame", row.names = c(NA, 
    -8L))

Upvotes: 0

akrun
akrun

Reputation: 887158

We can use split

split(df1[,2], df1[,1])
#$a1
#[1] 10 20 40

#$a2
#[1] 45 50

#$a3
#[1] 40

#$a4
#[1] 45 60

to create a list of vectors

Upvotes: 2

Related Questions