简体   繁体   中英

How to use rbind/cbind and avoid duplicates in R

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

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

With rbindlist and 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM