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

时间:2015-09-01 22:08:58

标签: r vector dataframe

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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