简体   繁体   中英

Convert entire data frame into one long column (vector)

I want to turn the entire content of a numeric (incl. NA's) data frame into one column. What would be the smartest way of achieving the following?

>df <- data.frame(C1=c(1,NA,3),C2=c(4,5,NA),C3=c(NA,8,9))
>df
     C1 C2 C3
  1  1  4 NA
  2 NA  5  8
  3  3 NA  9

>x <- mysterious_operation(df)
>x
[1] 1 NA 3 4 5 NA NA 8 9

I want to calculate the mean of this vector, so ideally I'd want to remove the NA's within the mysterious_operation - the data frame I'm working on is very large so it will probably be a good idea.

The mysterious operation you are looking for is called unlist :

> df <- data.frame(C1=c(1,NA,3),C2=c(4,5,NA),C3=c(NA,8,9))
> unlist(df, use.names = F)
[1]  1 NA  3  4  5 NA NA  8  9

Here's a couple ways with purrr :

# using invoke, a wrapper around do.call
purrr::invoke(c, df, use.names = FALSE)

# similar to unlist, reduce list of lists to a single vector
purrr::flatten_dbl(df)

Both return:

[1]  1 NA  3  4  5 NA NA  8  9

我们可以使用unlist并创建一个单列data.frame

df1 <- data.frame(col =unlist(df))

Just for fun. Of course unlist is the most appropriate function.

  1. alternative

    stack(df)[,1]

  2. alternative

    do.call(c,df)

    do.call(c,c(df,use.names=F)) #unnamed version

Maybe they are more mysterious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM