data.table语法通过tstrsplit根据其他表中的值设置colnames和values

时间:2022-08-13 08:04:41

after solving this issue and being still new to data.table I need help with a similar problem but cannot get it to work:

在解决了这个问题并且仍然是data.table的新手之后,我需要有类似问题的帮助,但无法让它工作:

I want to create a new dt that has the colnames of DT_1 split by [+-] as colnames

我想创建一个新的dt,其DT_的colnames被[+ - ]分割为colnames

DT_1= data.table("t+e+s+t" = c(8),"t+e+s-t" = c(8))
        t+e+s+t t+e+s-t
1:      8        8

and gets colnames of DT_2 as row entries

并获取DT_2的colnames作为行条目

DT_2 = data.table("+++-" = c("a","b"), "++-+" =c("e","f")) 

      +++- ++-+
1:    a    e
2:    b    f
3:    c    g
4:    d    h

so the final table looks like

所以决赛桌看起来像

   t   e   s   t
1: +   +   +   -
2: +   +   -   +

Since I need the entries of table DT_1 & DT_2 later on I want a new data.table. I tried:

由于我稍后需要表DT_1和DT_2的条目,我想要一个新的data.table。我试过了:

DT_final = data.table(str_split_fixed(colnames(DT_1), "[+-]")= c(tstrsplit(colnames(DT_2), "")))

It might not be possible to solve this in one line. Thanks for any help.

可能无法在一行中解决这个问题。谢谢你的帮助。

1 个解决方案

#1


2  

You could try:

你可以尝试:

result <- as.data.table(tstrsplit(names(DT_2), ""))
names(result) <- unlist(strsplit(names(DT_1)[1], "[+-]"))

> result
   t e s t
1: + + + -
2: + + - +

#1


2  

You could try:

你可以尝试:

result <- as.data.table(tstrsplit(names(DT_2), ""))
names(result) <- unlist(strsplit(names(DT_1)[1], "[+-]"))

> result
   t e s t
1: + + + -
2: + + - +