Home > other >  How to use rbind/cbind and avoid duplicates in R
How to use rbind/cbind and avoid duplicates in R

Time:09-01

I would like to insert one row of "comments" for a datatable or dataframe (type does not matter to me at this point).

Assume I have a datatable like this:

library(data.table)
DT = data.table(a = 3:4, c = 1:2, d=2:3)

I would like to insert one row with the string addthis, the rest of the cells can be NA (if you have better options, that would be best)

The output I want:

a       c       d 
addthis NA     NA
3       1      2
4       2      3

CodePudding user response:

Here's one approach, though there are probably better ways to do this:

DT = data.table(a = 3:4, c = 1:2, d=2:3)

text <- vector(mode="character", length=length(DT))
text[1] <- "addthis"
text <- as.data.frame(t(text))
colnames(text) <- c("a", "c", "d")

DT2 <- rbind(text,DT)

Here are the results:

        a c d
1 addthis    
2       3 1 2
3       4 2 3

CodePudding user response:

With rbindlist, with fill=TRUE option:

comment = data.table(a = 'add this')

rbindlist(list(comment,DT),fill=T)

          a     c     d
     <char> <int> <int>
1: add this    NA    NA
2:        3     1     2
3:        4     2     3

Note that this necessarily changes a field type to character (was integer)

  • Related