Eisen
Eisen

Reputation: 1887

Reformatting dataframe in R

I have a DF like so:

  (Intercept)        W          Q
1  0.09282078 2.370789 -0.2478352
2  0.11608078 1.890222 -0.3134176
3  0.09899802 1.764213 -0.1406203

how can I reformat it in dplyr to look like this:

Feature      coeff
1_intercept  0.09282078
1_W          2.370789
1_Q          -0.2478352
2_intercept  0.11608078
2_W          1.890222
2_Q          -0.3134176
3_intercept  0.09899802
3_W          1.764213
3_Q          -0.1406203

Upvotes: 2

Views: 47

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

Below is my base R attempt

transform(
  setNames(rev(stack(df)),c("Feature","coeff")),
  Feature = paste0(ave(seq_along(Feature), Feature, FUN = seq_along), "_", Feature)
)[order(rep(seq(ncol(df)),nrow(df))),]

which gives

        Feature       coeff
1 1_(Intercept)  0.09282078
4           1_W  2.37078900
7           1_Q -0.24783520
2 2_(Intercept)  0.11608078
5           2_W  1.89022200
8           2_Q -0.31341760
3 3_(Intercept)  0.09899802
6           3_W  1.76421300
9           3_Q -0.14062030

Upvotes: 0

akrun
akrun

Reputation: 887118

With tidyverse, we can do

library(dplyr)
library(tidyr)
df1 %>%
    as.data.frame %>%
    mutate(rn = row_number()) %>%
    pivot_longer(cols = -rn, names_to = 'Feature', values_to = 'coeff') %>%
    unite(Feature, rn, Feature, sep= "_")

Upvotes: 0

Related Questions