Search code examples
rdataframetranspose

Transpose dataframe as pattern changes in a column R


I have a data frame in R which looks like this with 3 columns

  col1 col2 col3
    A   11   203
    A   12   205
    C   25   306
    C   65   745

Desired output: Only the third column transposed when the pattern in first column changes.
I am new to R.

203   205
306   745

I tried t(data) but then it transposed the whole data.

For only the third column I tried t(data$col3) but this transposes the whole third column. I know I am close but couldn't make it.Any suggestion will be helpful. Thank you in advance.


Solution

  • Here is one way in Base-R

    t(sapply(split(df,df[,1]), function(x) x[,3]))
    
      [,1] [,2]
    A  203  205
    C  306  745
    

    Here, split is dividing the dataframe into smaller dataframes according to the letters in your first column. Then we pass a custom function(x) to those split dataframes using sapply. The custom function simply calls the values in the third column with x[,3].