简体   繁体   中英

Insert a list as new rows values in 1 column while duplicating the other columns

If I have a data.table:

d <- data.table(NUM = c(1, 2, 3),
               CLASS = c(1, 1, 1),
               VAR = c(4, 5, 3))

And a vector a <- c(7, 9, 10) .
How would I add the vector a with 1 value into a new row for column CLASS , while taking the first value from NUM and VAR and carrying it down?

Expected Output:

    NUM    CLASS    VAR
1      1       1      4
2      2       1      5
3      3       1      3
4      1       7      4
5      1       9      4
6      1      10      4

I want to find a streamlined way of carrying down the first value for all columns other than CLASS . Maybe with rbindlist ?

Yeah, rbind / rbindlist works:

rbind(
  d, 
  d[1, replace(as.list(.SD), names(.SD) == "CLASS", list(a))]
)

   NUM CLASS VAR
1:   1     1   4
2:   2     1   5
3:   3     1   3
4:   1     7   4
5:   1     9   4
6:   1    10   4

or more generally if there are other equal-length replacements...

rr = list(CLASS = a, VAR = 1:3)
rbind(
  d, 
  d[1, replace(as.list(.SD), match(names(rr), names(.SD)), rr)]
)

   NUM CLASS VAR
1:   1     1   4
2:   2     1   5
3:   3     1   3
4:   1     7   1
5:   1     9   2
6:   1    10   3

This could help:

CLASS <- c(7, 9, 10) 

e <- cbind(NUM=rep(d$NUM[1], nrow(d)), CLASS, VAR=rep(d$VAR[1], nrow(d))) 
e

d <- rbind(d, e)
d

# NUM CLASS VAR
# 1:   1     1   4
# 2:   2     1   5
# 3:   3     1   3
# 4:   1     7   4
# 5:   1     9   4
# 6:   1    10   4

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