r语言 - 返回第n个分割元素



我有一个字符列表的格式为deck/number/side,我想为deck和side创建单独的变量。

spaceTrainTib$Cabin变量如下:

[1]"B/0/P"F/0/S"一个/0/S"一个/0/S"F/1/S"F/0/P"F/2/S"G/0/S">
[9] F/3/S"B/1/P"B/1/P"B/1/P"F/1/P"G/1/S"F/2/P"NA
[17] "F/3/P"F/4/P"F/5/P"G/0/P"F/6/P"E/0/S"E/0/S"E/0/S">
[25] E/0/S"E/0/S"E/0/S"D/0/P"C/2/S"F/6/S"C/0/P"F/8/P">
[33] "G/4/S"F/9/P"F/9/P"F/9/P"D/1/S"D/1/P"F/8/S"F/10/S"[41]"G/1/P"G/2/P"B/3/P"G/3/P"G/3/P"G/3/P"F/10/P"F/10/P">

deck <- map_chr(str_split(spaceTrainTib$Cabin, "/"), 1)
deck

返回
[1] "B" "F" "A" "A" "F" "F" "F" "G" "F" "B" "B" "B" "F" "G" "F" NA  "F" "F" "F" "G" "F"
[22] "E" "E" "E" "E" "E" "E" "D" "C" "F" "C" "F" "G" "F" "F" "F" "D" "D" "F" "F" "G" "G"
[43] "B" "G" "G" "G" "F" "F" "E" "E" "G" "F" "A" "A" "A" "G" "F" "F" "F" "E" "G" "G" "G"

正在做它的工作。但是如果我使用

就行不通了
side <- map_chr(str_split(spaceTrainTib$Cabin, "/"), 3)
side

错误列表:" error in ' stop_bad_type()'! 结果16必须是单个字符串,而不是长度为0

的NULL。提取第三个字母。有人能帮忙吗?

我猜你在找这样的东西:

# using some of your data
some_string <- c("B/0/P", "F/0/S", "A/0/S", "A/0/S", "F/1/S", "F/0/P", "F/2/S", "G/0/S",
"F/3/S", "B/1/P", "B/1/P", "B/1/P", "F/1/P", "G/1/S", "F/2/P", NA)
# as experiment we try
unlist(strsplit(some_string, ' '))
[1] "B/0/P" "F/0/S" "A/0/S" "A/0/S" "F/1/S" "F/0/P" "F/2/S" "G/0/S" "F/3/S"
[10] "B/1/P" "B/1/P" "B/1/P" "F/1/P" "G/1/S" "F/2/P" NA
#then remove `/` from each triplet
new_string <- gsub('/', '', unlist(strsplit(some_string, ' ')))
[1] "B0P" "F0S" "A0S" "A0S" "F1S" "F0P" "F2S" "G0S" "F3S" "B1P" "B1P" "B1P"
[13] "F1P" "G1S" "F2P" NA 
deck <- substr(next_string, 1,1)
deck
[1] "B" "F" "A" "A" "F" "F" "F" "G" "F" "B" "B" "B" "F" "G" "F" NA 
side <- substr(next_string, 3, 3)
side
[1] "P" "S" "S" "S" "S" "P" "S" "S" "S" "P" "P" "P" "P" "S" "P" NA

的一种方法。

相关内容

  • 没有找到相关文章

最新更新