【问题标题】:Split and clean multiple length strings in a column to multiple columns using R script使用 R 脚本将一列中的多个长度字符串拆分并清理为多列
【发布时间】:2016-11-10 03:03:07
【问题描述】:

我有以下格式的数据:

test1 <- data.frame(value = c('25.5 (5%);  39.65 (23%)', '28.15(5%) and 55.66 (34%) and 33.26   (14%)', '45   56.9565', '95.6666 (55%)  89.2343(90%)   51.56 (28%)'))
test2 <- data.frame(value = c('36.5', '55.658', '47.8', '51.562'))

我需要将 test1 列中的值拆分为三列(col1、col2 和 col3),然后比较并突出显示列 (test2) 中与三列之一中的值相差 +/- 0.1 范围内的值列(col1、col2 和 col3),如下图所示。

请就如何进行此操作提出建议。

col1    col2    col3    test2
25.5    39.65           36.5
28.15   55.66   33.26   **55.658**
45      56.9565         47.8
95.6666 89.2343 51.56   **51.562**

string split (and cleaned) into columns

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用gsubread.table 将“值”列提取为三列

    df1 <- read.table(text=gsub("\\([^)]+\\)|[A-Za-z]+", "", test1$value), 
                        header=FALSE, fill=TRUE, col.names = paste0("col", 1:3))
    

    cbind它与'test2'

    df2 <- cbind(df1, test2)
    df2
    #    col1    col2  col3  value
    #1 25.5000 39.6500    NA   36.5
    #2 28.1500 55.6600 33.26 55.658
    #3 45.0000 56.9565    NA   47.8
    #4 95.6666 89.2343 51.56 51.562
    

    更新

    有了新数据

    cbind(read.table(text=gsub("\\([^)]+\\)|[A-Za-z]+|[;,]\\s*", "", 
       test1$value), header=FALSE, fill=TRUE, col.names = paste0("col", 1:3)), test2)
    #    col1    col2  col3  value
    #1 25.5000 39.6500    NA   36.5
    #2 28.1500 55.6600 33.26 55.658
    #3 45.0000 56.9565    NA   47.8
    #4 95.6666 89.2343 51.56 51.562
    

    【讨论】:

    • 谢谢@akrun。过去 3 天我一直在努力解决这个问题,而你在 3 秒内解决了这个问题。伟大的!我非常感谢你的技巧和善意。
    • 如果括号后有分号或逗号,例如:test1
    • @RanonKahn 在这种情况下,cbind(read.table(text=gsub("\\([^)]+\\)|[A-Za-z]+|[;,]\\s*", "", test1$value), header=FALSE, fill=TRUE, col.names = paste0("col", 1:3)), test2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多