【问题标题】:Split dataframe character into columns based on value of character [duplicate]根据字符的值将数据框字符拆分为列[重复]
【发布时间】:2020-03-31 17:27:08
【问题描述】:

有没有办法根据数据框中字符的值将数据拆分为多列,例如,我从这个数据框开始

initialData = data.frame(attr = c('a','b','c','d'), type=c('1,2','2','3','2 ,3'))

endData 是这样的:

    attr    Conditions  Cond1   Cond2   Cond3
1   a       1,2         TRUE    TRUE    FALSE
2   b       2           FALSE   TRUE    FALSE
3   c       3           FALSE   FALSE   TRUE
4   d       2,3         FALSE   TRUE    TRUE

我编写了一个函数,它接收一个字符,对其执行正则表达式以查看是否满足条件,然后返回 true 或 false,但我不确定如何遍历数据框中的每一行并添加到正确的列

【问题讨论】:

    标签: r


    【解决方案1】:

    strsplitcbind 的“类型”列与原始数据集拆分后,我们可以使用qdapTools 中的mtabulate

    library(qdapTools)
    out <- cbind(initialData, 
         mtabulate(strsplit(as.character(initialData$type), ",")) > 0)
    names(out)[3:5] <- paste0("Cond", names(out)[3:5])
    out
    #   attr type Cond1 Cond2 Cond3
    #1    a  1,2  TRUE  TRUE FALSE
    #2    b    2 FALSE  TRUE FALSE
    #3    c    3 FALSE FALSE  TRUE
    #4    d  2,3 FALSE  TRUE  TRUE
    

    【讨论】:

    • 非常感谢,感谢您的帮助。这解决了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2011-05-20
    相关资源
    最近更新 更多