英文:
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("S01_28819_W0D0_Unpr", "S01_28819_W0D1_Unpr", "S01_28819_W0D3_Unpr")
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 <- data.frame(admin=character(), type=character(), time=character(), cond=character())
for (i in qwerty) {
i <- unlist(strsplit(i, "_"))
}
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 = '_'
:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论