gpt4 book ai didi

string - 定期拆分字符串

转载 作者:行者123 更新时间:2023-12-04 16:31:45 24 4
gpt4 key购买 nike

我想定期分割一个字符串。我的问题几乎与此相同:How to split a string into substrings of a given length?除了我在数据集中有一列字符串而不是一个字符串。

这是一个示例数据集:

df = read.table(text = "
my.id X1
010101 1
010102 1
010103 1
010104 1
020101 1
020112 1
021701 0
021802 0
133301 0
133302 0
241114 0
241215 0
", header = TRUE, colClasses=c('character', 'numeric'), stringsAsFactors = FALSE)

这是想要的结果。我宁愿删除前导零,如图所示:
desired.result = read.table(text = "
A1 A2 A3 X1
1 1 1 1
1 1 2 1
1 1 3 1
1 1 4 1
2 1 1 1
2 1 12 1
2 17 1 0
2 18 2 0
13 33 1 0
13 33 2 0
24 11 14 0
24 12 15 0
", header = TRUE, colClasses=c('numeric', 'numeric', 'numeric', 'numeric'), stringsAsFactors = FALSE)

这是一个似乎接近的循环,也许我可以使用它。但是,我认为可能有更有效的方法。
for(i in 1:nrow(df)) {
print(substring(df$my.id[i], seq(1, 5, 2), seq(2, 6, 2)))
}

apply声明不起作用:
apply(df$my.id, 1,  function(x) substring(df$my.id[x], seq(1, 5, 2), seq(2, 6, 2))   )

谢谢你的任何建议。我更喜欢基础 R 中的解决方案。

最佳答案

我发现 read.fwf应用于 textConnection是解决此问题的各种方法中最有效和最易于理解的。它具有内置在 read.* 函数中的自动类检测的优点。

cbind( read.fwf(file=textConnection(df$my.id), 
widths=c(2,2,2), col.names=paste0("A", 1:3)),
X1=df$X1)
#-----------
A1 A2 A3 X1
1 1 1 1 1
2 1 1 2 1
3 1 1 3 1
4 1 1 4 1
5 2 1 1 1
6 2 1 12 1
7 2 17 1 0
8 2 18 2 0
9 13 33 1 0
10 13 33 2 0
11 24 11 14 0
12 24 12 15 0

(我相信我是在大约 6 年前在 Rhelp 上从 Gabor Grothendieck 那里学到的。)

如果您更喜欢正则表达式策略,请查看此策略,它每两个位置插入一个制表符并通过 read.table 运行它。非常紧凑:
read.table(text=gsub('(.{2})','\\1\t',df$my.id) )
#---------
V1 V2 V3
1 1 1 1
2 1 1 2
3 1 1 3
4 1 1 4
5 2 1 1
6 2 1 12
7 2 17 1
8 2 18 2
9 13 33 1
10 13 33 2
11 24 11 14
12 24 12 15

关于string - 定期拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14948018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com