Achal Neupane
Achal Neupane

Reputation: 5719

How to insert new row in a dataframe to make it equal row number as the length of given vector in R

I have a dataframe called mydf and a vector called myvec. The number of rows in dataframe is smaller than the length of the vector. I want to expand the dataframe by inserting the vector element if it is not in the rowname of the dataframe.

myvec <- c("apple", "banana", "grapes", "oranges")

mydf

rowname   codes    remark
apple     44        bad
grapes    54        good

result

rowname   codes    remark
  apple     44        bad
  banana
  grapes    54        good
  oranges

Upvotes: 2

Views: 70

Answers (3)

akrun
akrun

Reputation: 887681

Using data.table

library(data.table)
setDT(mydf)[setDT(list(rowname=myvec)), on='rowname']
#   rowname codes remark
#1:   apple    44    bad
#2:  banana    NA     NA
#3:  grapes    54   good
#4: oranges    NA     NA

Upvotes: 2

Marat Talipov
Marat Talipov

Reputation: 13304

You can convert myvec into a dataframe and use merge:

merge(d,data.frame(rowname=myvec),all.y=TRUE)
#   rowname codes remark
# 1   apple    44    bad
# 2  grapes    54   good
# 3  banana    NA   <NA>
# 4 oranges    NA   <NA>

Upvotes: 4

rawr
rawr

Reputation: 20811

Are the rownames actually rownames? You could do this if you don't subscribe to the hadley opinion of rownames

myvec <- c("apple", "banana", "grapes", "oranges")
dd <- read.table(header = TRUE, stringsAsFactors = FALSE,
text = 'rowname   codes    remark
apple     44        bad
grapes    54        good')

rownames(dd) <- dd$rowname
#        rowname codes remark
# apple    apple    44    bad
# grapes  grapes    54   good



`rownames<-`(dd[myvec, ], myvec)

#           rowname codes remark
#   apple     apple    44    bad
#   banana     <NA>    NA   <NA>
#   grapes   grapes    54   good
#   oranges    <NA>    NA   <NA>

Upvotes: 3

Related Questions