0

When I bind multiple dataframes together using Out2 = do.call(rbind.data.frame, Out), I obtain the following output. How do I relabel the first column such that it only contains the numbers within the square brackets, i.e. 1 to 5 for each trial number? Is there a way to add a column name to the first column too?

      |      V1      |      V2      | Trial |
+--------+--------------+--------------+-------+
|  [1,]  |  0.130880519 |   0.02085533 |     1 |
|  [2,]  |  0.197243133 | -0.000502744 |     1 |
|  [3,]  | -0.045241653 |  0.106888902 |     1 |
|  [4,]  |  0.328759949 | -0.106559163 |     1 |
|  [5,]  |  0.040894969 |  0.114073454 |     1 |
|  [1,]1 |  0.103130056 |  0.013655756 |     2 |
|  [2,]1 |  0.133080106 |  0.038049071 |     2 |
|  [3,]1 |  0.067975054 |   0.03036033 |     2 |
|  [4,]1 |  0.132437217 |  0.022887103 |     2 |
|  [5,]1 |  0.124950463 |  0.007144698 |     2 |
|  [1,]2 |  0.202996317 |  0.004181205 |     3 |
|  [2,]2 |  0.025401354 |  0.045672932 |     3 |
|  [3,]2 |  0.169469266 |  0.002551237 |     3 |
|  [4,]2 |    0.2303046 |  0.004936579 |     3 |
|  [5,]2 |  0.085702254 |  0.020814191 |     3 |
+--------+--------------+--------------+-------+
aynber
  • 22,380
  • 8
  • 50
  • 63
sjedi
  • 43
  • 1
  • 7

1 Answers1

0

We can use parse_number to extract the first occurence of numbers

library(dplyr)
df1 %>%
   mutate(newcol = readr::parse_number(row.names(df1)))

Or in base R, use sub to capture the digits after the [ in the row names

df1$newcol <- sub("^\\[(\\d+).*", "\\1", row.names(df1))
akrun
  • 874,273
  • 37
  • 540
  • 662