Replace index column in dataframe

4k views Asked by At

I’m trying to do a heatmap with a dataset using "d3heatmap".

I have a dataframe whose first column contains the name of soccer players. However, I'm getting the following error because that column in not numeric.

Error in rowMeans(x, na.rm = na.rm) : 'x' must be numeric"

+----------------------+--------------------+---------+-------+
| Index column         | Player             | Minutes | Goals |
+----------------------+--------------------+---------+-------+
| 1                    |             Robert | 1234    | 10    |
| 2                    |             John   | 1253    | 15    |
| 3                    |             Mark   | 112     | 1     |
+----------------------+--------------------+---------+-------+

How could I replace the index column of a data frame with my first column (player)?

Ideal situation

+--------------------+---------+-------+
| Player             | Minutes | Goals |
+--------------------+---------+-------+
|             Robert | 1234    | 10    |
|             John   | 1253    | 15    |
|             Mark   | 112     | 1     |
+--------------------+---------+-------+

I'm trying to search for similar questions but I haven't got the answer.

Thanks a lot for your help in advance. Much appreciated.

Thanks, Juanma

1

There are 1 answers

3
Rui Barradas On BEST ANSWER

I'm not sure if you want dat2 or dat3 below. In fact, I'm not sure that Index column is a column in your original data.frame, I will assume that it is.

dat <- data.frame(
        index = 1:3,
        Player = c("Robert", "John", "Mark"),
        Minutes = c(1234, 1253, 112),
        Goals = c(10, 15, 1)
    )

dat
dat2 <- dat[, -1]
dat2
  Player Minutes Goals
1 Robert    1234    10
2   John    1253    15
3   Mark     112     1

In the next case, dat3, I've eliminated the column Player and transformed its values in the row names.

dat3 <- dat[, -(1:2)]
rownames(dat3) <- dat$Player
dat3
       Minutes Goals
Robert    1234    10
John      1253    15
Mark       112     1