Home > Net >  Add new columns with defined values in R
Add new columns with defined values in R

Time:04-23

I have a data.table named dmat. I want to add each character of missing_snps to dmat as new column and assign all rows as zero. The output remains in the same class as it was. I would appreciate any suggestion.

dmat <- structure(list(`1:27950613:G:A` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27950883:CTA:C` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27952180:A:G` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27953106:A:G` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27953374:G:T` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27953514:T:TA` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27953608:T:C` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27954027:G:A` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27954415:T:C` = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), `1:27962685:T:C` = c(0L, 0L, 0L, 0L, 0L, 1L, 0L, 
0L, 0L, 0L)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
"data.frame"))

missing_snps <- c("1:169858888:G:A", "1:16985867657:T:A", "1:132862874:G:A")

CodePudding user response:

dmat[,c("1:169858888:G:A", "1:16985867657:T:A", "1:132862874:G:A")] <- 0

or dmat[, missing_snps] <- 0

CodePudding user response:

Using data.table,

dmat <- setDT(dmat)
missing_snps <- c("1:169858888:G:A", "1:16985867657:T:A", "1:132862874:G:A")
dmat[,(missing_snps ):=0]

Output

> dmat[,..missing_snps ]
    1:169858888:G:A 1:16985867657:T:A 1:132862874:G:A
 1:               0                 0               0
 2:               0                 0               0
 3:               0                 0               0
 4:               0                 0               0
 5:               0                 0               0
 6:               0                 0               0
 7:               0                 0               0
 8:               0                 0               0
 9:               0                 0               0
10:               0                 0               0

The columns you want to mutate has been added.

  • Related