'How add a row of 0 to a dataframe
I have this dataframe in R
mat <-structure(list(a = c(2, 5, 90, 77, 56), b = c(45, 78, 98, 55,
63), c = c(77, 85, 3, 22, 4), d = c(52, 68, 4, 25, 79), e = c(14,
73, 91, 87, 94)), class = "data.frame", row.names = c(NA, -5L
))
and I want add a row of "0" as first row of mat. The output that I need is
a b c d e
1 0 0 0 0 0
2 2 45 77 52 14
3 5 78 85 68 73
4 90 98 3 4 91
5 77 55 22 25 87
6 56 63 4 79 94
How can I do? Thx
Solution 1:[1]
We can use rbind
mat <- rbind(0, mat)
-output
mat
a b c d e
1 0 0 0 0 0
2 2 45 77 52 14
3 5 78 85 68 73
4 90 98 3 4 91
5 77 55 22 25 87
6 56 63 4 79 94
Solution 2:[2]
Here is another option using tidyverse, where we iterate through each column to add a 0 to the first position, then bind back together as a dataframe.
library(tidyverse)
map_df(mat, ~ c(0, .x))
Output
a b c d e
<dbl> <dbl> <dbl> <dbl> <dbl>
1 0 0 0 0 0
2 2 45 77 52 14
3 5 78 85 68 73
4 90 98 3 4 91
5 77 55 22 25 87
6 56 63 4 79 94
Or another option would be to keep only the first row of the dataframe, then change all the values to 0, then use bind_rows to add to mat.
bind_rows(mutate(mat[1, ], across(everything(), ~ 0)), mat)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akrun |
| Solution 2 | AndrewGB |
