R:gsub和str_split_fixed在data.tables中 [英] R: gsub and str_split_fixed in data.tables

查看:97
本文介绍了R:gsub和str_split_fixed在data.tables中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从data.frame转换为data.table

I am "converting" from data.frame to data.table

我现在有一个data.table:

I now have a data.table:

library(data.table)


DT = data.table(ID = c("ab_cd.de","ab_ci.de","fb_cd.de","xy_cd.de"))
DT

         ID
1: ab_cd.de
2: ab_ci.de
3: fb_cd.de
4: xy_cd.de  

new_DT<- data.table(matrix(ncol = 2))
colnames(new_DT)<- c("test1", "test2")

我要首先:删除 .de在每个条目之后和下一步中,用下划线将每个条目分开,并将输出保存在两个新列中。最终输出应如下所示:

I would like to to first: delete ".de" after every entry and in the next step separate every entry by the underscore and save the output in two new columns. The final output should look like this:

   test1 test2
1    ab    cd
2    ab    ci
3    fb    cd
4    xy    cd

在data.frame中,我这样做:

In data.frame I did:

df = data.frame(ID = c("ab_cd.de","ab_ci.de","fb_cd.de","xy_cd.de"))
df

         ID
1: ab_cd.de
2: ab_ci.de
3: fb_cd.de
4: xy_cd.de


df[,1] <- gsub(".de", "", df[,1], fixed=FALSE)
df

      ID
1: ab_cd
2: ab_ci
3: fb_cd
4: xy_cd



 n <- 1
for (i in (1:length(df[,1]))){
    new_df[n,] <-str_split_fixed(df[i,1], "_", 2)
    n <- n+1
}
new_df

  test1 test2
1    ab    cd
2    ab    ci
3    fb    cd
4    xy    cd

感谢您的帮助!

推荐答案

您可以使用 tstrsplit 将列拆分为两个r用 sub 删除后缀( .de ):

You can use tstrsplit to split the column into two after removing the suffix (.de) with sub:

DT[, c("test1", "test2") := tstrsplit(sub("\\.de", "", ID), "_")][, ID := NULL][]

#   test1 test2
#1:    ab    cd
#2:    ab    ci
#3:    fb    cd
#4:    xy    cd

这篇关于R:gsub和str_split_fixed在data.tables中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆