在R中的数据帧列表中拆分列

时间:2019-10-24 06:41:32

标签: r

我有一个数据帧列表,其中某些列带有特殊字符-> (箭头)。现在,我确实想遍历此数据帧列表,并使用-> (箭头)定位列,然后用后缀_old和_new命名新列。这是数据帧的示例:

dput(df1)
df1 <- structure(list(v1 = c("reg->joy", "ress", "mer->dls"),
                      t2 = c("James","Jane", "Egg")),
                 class = "data.frame", row.names = c(NA,  -3L))

dput(df2)
df2 <- structure(list(v1 = c("me", "df", "kl"),
                      t2 = c("James","Jane->dlt", "Egg"),
                      t3 = c("James ->may","Jane", "Egg")),
                 class = "data.frame", row.names = c(NA,  -3L))
dput(df3)
df3 <- structure(list(v1 = c("56->34", "df23-> ", "mkl"),
                      t2 = c("James","Jane", "Egg"),
                      d3 = c("James->","Jane", "Egg")),
                 class = "data.frame", row.names = c(NA,  -3L))

这是我尝试过的

dfs <- list(df1,df2,df3)

for (y in 1:length(dfs)){
  setDT(dfs[[y]])
  df1<- lapply(names(dfs[[y]]), function(x) {
    mDT <- df2[[y]][, tstrsplit(get(x), " *-> *")]
    if (ncol(mDT) == 2L) setnames(mDT, paste0(x, c("_old", "_new")))
  }) %>% as.data.table()

}

这只会拆分一个数据帧,我需要拆分所有数据帧

预期输出


dput(df1)
df1 <- structure(list(v1_old = c("reg", "mer"),
                      v1_new = c("joy", "dls")),
                 class = "data.frame", row.names = c(NA,  -3L))

dput(df2)
df2 <- structure(list(t2_old = c("dlt"),
                      t2_new = c("dlt"),
                      t3_old = c("James"),
                      t3_new = c("may")),
                 class = "data.frame", row.names = c(NA,  -3L))

dput(df3)
df3 <- structure(list(v1_old = c("56", "df23 "),
                      v1_new = c("34", " "),
                      d3 = c("James"),
                      d3 = c(" ")),
                 class = "data.frame", row.names = c(NA,  -3L))

1 个答案:

答案 0 :(得分:0)

所以我到处玩耍并找到了答案

df1 <-c()
for (y in 1:length(dfs)){
  setDT(dfs[[y]])
  df1[[y]] <- lapply(names(modifiedtbl[[y]]), function(x) {
    mDT <- dfs[[y]][, tstrsplit(get(x), " *-> *")]
    if (ncol(mDT) == 2L) setnames(mDT, paste0(x, c("_old", "_new")))
  }) %>% as.data.table()

}