0

I am trying to rename the columns of my data frame with the row values. I have the following:

                FIRM TIME          V_Ri
1   A EAGLE 14DEC1994  740 -0.0005039933
2   A EAGLE 14DEC1994  741  0.0000000000
3   A EAGLE 14DEC1994  742  0.0238607800
4   A EAGLE 14DEC1994  743 -0.0125612300
5   A EAGLE 14DEC1994  744 -0.0134325100

And I would like to obtain:

                 FIRM            740          741    etc.
1   A EAGLE 14DEC1994  -0.0005039933 0.0000000000

I have tried by transposing, but couldn't reach the desired result. Any hints?

2 Answers 2

0

Base R one-liner (Thanks @Ben Norris for the dataset):

spread_df <- as.data.frame.matrix(xtabs(V_Ri ~ FIRM+TIME, df))

If you want to reset the index column and push the row.names back to a FIRM vector:

data.frame(FIRM = row.names(spread_df), spread_df, row.names = NULL)
0
0

This is a problem for pivot_wider() from the tidyr package.

If your data is in a data.frame called df, do the following:

library(tidyr)

df %>%
  pivot_wider(names_from = "TIME", values_from = "V_Ri")

# A tibble: 1 x 6
  FIRM                  `740` `741`  `742`   `743`   `744`
  <chr>                 <dbl> <dbl>  <dbl>   <dbl>   <dbl>
1 A EAGLE 14DEC1994 -0.000504     0 0.0239 -0.0126 -0.0134

Note that the column names have back ticks around the numbers. Names of objects, including column names, are not typically allowed to start with numerals. The back tick encapsulates nonstandard names.

Sample data used:

df <- structure(list(FIRM = c("A EAGLE 14DEC1994", "A EAGLE 14DEC1994", 
                              "A EAGLE 14DEC1994", "A EAGLE 14DEC1994", 
                              "A EAGLE 14DEC1994"), 
                     TIME = c(740, 741, 742, 743, 744), 
                     V_Ri = c(-0.0005039933, 0, 0.02386078, -0.01256123, 
                              -0.01343251)), 
                row.names = c(NA, -5L), 
                class = c("tbl_df", "tbl", "data.frame"))
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.