1

Assume I have the following short example. My goal is to rearrange the data.frame by column "n", so that the output looks as shown below. Since I am still the beginner I don't know how to do this. I tried with reshape2.

         Method   n    lambda     df       
10.fold.CV Lasso 30  1.3102653 21.199    
10.fold.CV.1SE   30  3.3734592 17.379 
10.fold.CV Lasso 50  0.8956816 28.713 
10.fold.CV.1SE   50  2.3527001 25.540 
BIC              50  1.9833844 24.757 
Modified.BIC     50  0.2091384 31.714 
10.fold.CV Lasso 100 0.6467475 33.591  
10.fold.CV.1SE   100 2.4961030 32.092

The expected output should look like this:

                  Lambda30  df30      Lambda50  df50   Lambda100 df100     
10.fold.CV Lasso  1.3102653 21.199   0.8956816 28.713  0.6467475 33.591 
10.fold.CV.1SE    2.3527001 25.540   3.3734592 17.379  2.4961030 32.092
BIC                                  1.9833844 24.757   ..
Modified.BIC                         0.2091384 31.714   ..
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
Leo96
  • 489
  • 3
  • 12

1 Answers1

3

You can do the following

library(tidyverse);
df %>%
    gather(k, v, -Method, -n) %>%
    unite(tmp, k, n, sep = "_") %>%
    spread(tmp, v)
#            Method df_100  df_30  df_50 lambda_100 lambda_30 lambda_50
#1 10.fold.CV Lasso 33.591 21.199 28.713  0.6467475  1.310265 0.8956816
#2   10.fold.CV.1SE 32.092 17.379 25.540  2.4961030  3.373459 2.3527001
#3              BIC     NA     NA 24.757         NA        NA 1.9833844
#4     Modified.BIC     NA     NA 31.714         NA        NA 0.2091384

Explanation: Within the tidyverse, this is a fairly straightforward matter of reshaping from wide to long using tidyr::gather, tidyr::uniteing columns, and reshaping from long to wide using tidyr::spread.

If necessary, reorder columns with e.g. select.


Sample data

df <- read.table(text =
    "         Method   n    lambda     df
'10.fold.CV Lasso' 30  1.3102653 21.199
10.fold.CV.1SE   30  3.3734592 17.379
'10.fold.CV Lasso' 50  0.8956816 28.713
10.fold.CV.1SE   50  2.3527001 25.540
BIC              50  1.9833844 24.757
Modified.BIC     50  0.2091384 31.714
'10.fold.CV Lasso' 100 0.6467475 33.591
10.fold.CV.1SE   100 2.4961030 32.092", header = T)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68