将字符串转换为数据框的列

huangapple go评论63阅读模式
英文:

Convert character string into columns of dataframe

问题

我有一个看起来像这样的字符向量:

c("S01_28819_W0D0_Unpr", "S01_28819_W0D1_Unpr", "S01_28819_W0D3_Unpr")

我想要做的是使用 "_" 作为分隔符拆分每个条目,然后将它们添加到一个新的数据框中,使其看起来像这样:

   admin   type   time  cond
1   S01   28819   W0D0   Unpr
2   S01   28819   W0D1   Unpr
3   S01   28819   W0D3   Unpr

到目前为止,我已经初始化了一个新的数据框,然后使用for循环来拆分每个条目。

df <- data.frame(admin=character(), type=character(), time=character(), cond=character())

for (i in qwerty) {
    i <- unlist(strsplit(i, "_"))
}

我卡在如何将拆分的字符字符串添加到数据框中。任何帮助将不胜感激。谢谢。

英文:

I have a character vector that looks like this:

c(&quot;S01_28819_W0D0_Unpr&quot;, &quot;S01_28819_W0D1_Unpr&quot;, &quot;S01_28819_W0D3_Unpr&quot;)

What I would like to do is split each entry using "_" as the separator then add those to a new dataframe so that it would look like this:

      admin  type time cond
    1   S01 28819 W0D0 Unpr
    2   S01 28819 W0D1 Unpr
    3   S01 28819 W0D3 Unpr

So far, I've initialized a new dataframe and then used a for loop to split each entry.

    df &lt;- data.frame(admin=character(), type=character(), time=character(), cond=character())

    for (i in qwerty) {
        i &lt;- unlist(strsplit(i, &quot;_&quot;))
    }

Where I'm stuck is in how to add the split character strings to the dataframe. Any help would be much appreciated. Thanks.

答案1

得分: 2

使用 read.table 时设置 sep = '_'

c("S01_28819_W0D0_Unpr", "S01_28819_W0D1_Unpr", "S01_28819_W0D3_Unpr") -> string

read.table(text = string, sep = '_')
   V1    V2   V3   V4
1 S01 28819 W0D0 Unpr
2 S01 28819 W0D1 Unpr
3 S01 28819 W0D3 Unpr

data.frame(do.call(rbind, strsplit(string, "_")))
   X1    X2   X3   X4
1 S01 28819 W0D0 Unpr
2 S01 28819 W0D1 Unpr
3 S01 28819 W0D3 Unpr
英文:

use read.table with sep = &#39;_&#39;:

c(&quot;S01_28819_W0D0_Unpr&quot;, &quot;S01_28819_W0D1_Unpr&quot;, &quot;S01_28819_W0D3_Unpr&quot;) -&gt; string

read.table(text = string, sep = &#39;_&#39;)
   V1    V2   V3   V4
1 S01 28819 W0D0 Unpr
2 S01 28819 W0D1 Unpr
3 S01 28819 W0D3 Unpr

data.frame(do.call(rbind, strsplit(string, &quot;_&quot;)))
   X1    X2   X3   X4
1 S01 28819 W0D0 Unpr
2 S01 28819 W0D1 Unpr
3 S01 28819 W0D3 Unpr

huangapple
  • 本文由 发表于 2023年6月2日 04:49:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定