Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding named rows to a data.frame in R

Tags:

dataframe

r

Maybe this is too simple of a question, but I'm trying to add 2 more named rows to data.frame d below without success.

Would you please help me understand what I'm missing, and correcting my approach?

d <- data.frame(ESL = 1:5, prof = 0:4, scope = 2:6, type = 3:7)
rownames(d) <- LETTERS[1:5]
d[6:7,] <- c(com = 0:3, min = 2:5)
d

# DESIRED OUTPUT:
#   ESL prof scope type
# A   1    0     2    3
# B   2    1     3    4
# C   3    2     4    5
# D   4    3     5    6
# E   5    4     6    7
# com 0    1     2    3
# min 2    3     4    5
like image 850
rnorouzian Avatar asked Mar 01 '26 18:03

rnorouzian


2 Answers

Use rbind to form the right hand side and specify the rownames on the left hand side.

d[c("com", "min"),] <- rbind(0:3, 2:5)
like image 80
G. Grothendieck Avatar answered Mar 04 '26 07:03

G. Grothendieck


You can use rbind() on the named vectors.

rbind(d, com = 0:3, min = 2:5) 

    ESL prof scope type
A     1    0     2    3
B     2    1     3    4
C     3    2     4    5
D     4    3     5    6
E     5    4     6    7
com   0    1     2    3
min   2    3     4    5
like image 44
Ritchie Sacramento Avatar answered Mar 04 '26 09:03

Ritchie Sacramento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!