user3242680
user3242680

Reputation: 63

Create a one column vector out of a data frame in r

What I'm looking for is to create a vector out of a data frame in r. Basically what I have is a data frame with four columns (1 to 4) and four rows (A to D) and its values (a.1, a.2, etc.) like this:

     1    2    3    4
A   a.1  a.2 ...   
B   b.1
C
D

What I want is to create one vector with the row names A1, A2,..., B1,...D4 and its values like this, but I don't know how:

   value
A1 a.1
A2 a.2
B1 b.1

Upvotes: 2

Views: 2963

Answers (2)

thelatemail
thelatemail

Reputation: 93938

Some variation on this, keeping with base R functions:

data.frame(value=unlist(df), row.names=outer(rownames(df), colnames(df), paste0))
#   value
#a1     a
#b1     b
#a2     b
#b2     c

Source data:

df <- data.frame(`1`=c("a","b"),`2`=c("b","c"),row.names=c("a","b"),check.names=FALSE)
#  1 2
#a a b
#b b c

Upvotes: 3

David Arenburg
David Arenburg

Reputation: 92300

You could create an index column using your row names and then melt the data accordingly and then rename your row names according to your two new columns, something like

library(reshape2)
df$indx <- row.names(df)
res <- melt(df, "indx")
row.names(res) <- with(res, paste0(indx, variable))
res["value"]
#    value
# A1   a.1
# B1   b.1
# C1   c.1
# D1   d.1
# A2   a.2
# B2   b.2
# C2   c.2
# D2   d.2
# A3   a.3
# B3   b.3
# C3   c.3
# D3   d.3
# A4   a.4
# B4   b.4
# C4   c.4
# D4   d.4

Upvotes: 2

Related Questions