简体   繁体   中英

How to convert one single column to row in R?

Here is one example table:

data.frame(A = c(1,2,3),
  B = c(2,4,2), 
  C = c(5,2,1), 
  class = c('apple', 'pear', 'banana'))

A   B   C   class
1   2   5   apple   
2   4   2   pear    
3   2   1   banana

The final result I want to get:

name  apple  pear  banana
A     1      2     3    
B     2      4     2    
C     5      2     1    

I have tried both gather() and spread() from tidyr package but they were not the way I want. FYI, the dimension of the original table is 1000*150, so a reproductive way would be greatly appreciated.

Using gather and spread will give you the output you want:

> library(tidyr)
> df1 %>% gather(cols, values, A:C) %>% 
    spread(class, values)
  cols apple banana pear
1    A     1      3    2
2    B     2      2    4
3    C     5      1    2

You can even use melt and dcast from reshape2 package

> library(reshape2)
> dcast(melt(df1), variable ~ class)
Using class as id variables
  variable apple banana pear
1        A     1      3    2
2        B     2      2    4
3        C     5      1    2

Convert the class column to rownames, transpose, convert to data frame and convert the rownames to the name column.

library(magrittr)
library(tibble)

DF %>% 
   column_to_rownames("class") %>% 
   t %>% 
   as.data.frame %>% 
   rownames_to_column("name")

giving:

  name apple pear banana
1    A     1    2      3
2    B     2    4      2
3    C     5    2      1

Here is a base R solution using transpose:

df <- data.frame(A,B,C, class, stringsAsFactors=FALSE)
out <- data.frame(t(df[c("A", "B", "C")]))
out <- cbind(names(df)[1:3], out)
names(out) <- c("name", df$class)
out

  name apple pear banana
A    A     1    2      3
B    B     2    4      2
C    C     5    2      1

Demo

I suggest using

t()

the transpose function.

Let

df <- data.frame(A = c(1,2,3),
B = c(2,4,2), 
C = c(5,2,1), 
class = c('apple', 'pear', 'banana'))

Before transposing, remove the column that you want as the column names in the final dataframe. In this case column 4,

new_colnames <- df[,4]
df <- df[,-4]

then transpose df,

df <- t(df)

then set the colnames to new_colnames.

colnames(df) <- new_colnames

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