SaZa
SaZa

Reputation: 311

convert a dataframe to a numeric variable?

I have a a variable with data.frame format and with size (m by n) and I want to convert it to a (m*n by 1) numeric variable. How can I do that? for example having variable "x1" with class of "data.frame" and size (4*5)

x1<-                
104.89  44.09   66.82   75.55   64.04
NA         136.91   60.57   62.29   64.01
NA         NA   87.18   66.76   80.19
NA         NA   NA  NA  NA

I want to convert "x1" to variable "x2" as below with size (20*1) and class of "numeric"

x2 <- 104.89    44.09   66.82   75.55   64.04       NA  136.91  60.57   62.29   64.01       NA         NA   87.18   66.76   80.19       NA         NA   NA  NA  NA

Upvotes: 0

Views: 123

Answers (2)

Henrik
Henrik

Reputation: 67778

Does this do what you want?

c(t(x1))

Upvotes: 2

sckott
sckott

Reputation: 5893

Since it looks like your use case is a matrix with values only in one corner, you can use upper.tri. E.g.

df=read.table(textConnection('
    104.89  44.09   66.82   75.55   64.04
    NA         136.91   60.57   62.29   64.01
    NA         NA   87.18   66.76   80.19
    NA         NA   NA  NA  NA'))
temp <- df[upper.tri(df)]
temp[!sapply(temp, is.na)]

[1] 44.09 66.82 60.57 75.55 62.29 66.76 64.04 64.01 80.19

Upvotes: 0

Related Questions