r-将子集转换为前缀版本以使用管道



我需要将矩阵子集[, 2:3]操作转换为前缀版本'['(,目前遇到了问题。我必须用哪种方法来纠正下面的代码?

library(tidyverse)
d <- tibble(x = str_c(letters[1:10], letters[1:10], letters[1:10], sep = "_"))
d %>% 
pull(x) %>%
str_split("_", simplify = TRUE) %>%
`[`(c(2, 3)) # ???
# want in terms of result not code:
d %>%
pull(x) %>%
str_split("_", simplify = TRUE) -> tmp
tmp[, 2:3] 
# [,1] [,2]
# [1,] "a"  "a" 
# [2,] "b"  "b" 
# [3,] "c"  "c" 
# [4,] "d"  "d" 
# [5,] "e"  "e" 
# [6,] "f"  "f" 
# [7,] "g"  "g" 
# [8,] "h"  "h" 
# [9,] "i"  "i" 
# [10,] "j"  "j" 

可能最简单的事情是使用.

d %>% 
pull(x) %>%
str_split("_", simplify = TRUE) %>%
.[, 2:3]
#       [,1] [,2]
#  [1,] "a"  "a" 
#  [2,] "b"  "b" 
#  [3,] "c"  "c" 
#  [4,] "d"  "d" 
#  [5,] "e"  "e" 
#  [6,] "f"  "f" 
#  [7,] "g"  "g" 
#  [8,] "h"  "h" 
#  [9,] "i"  "i" 
# [10,] "j"  "j" 

但如果你想,你也可以做

d %>% 
pull(x) %>%
str_split("_", simplify = TRUE) %>%
'['(, 2:3)
#       [,1] [,2]
#  [1,] "a"  "a" 
#  [2,] "b"  "b" 
#  [3,] "c"  "c" 
#  [4,] "d"  "d" 
#  [5,] "e"  "e" 
#  [6,] "f"  "f" 
#  [7,] "g"  "g" 
#  [8,] "h"  "h" 
#  [9,] "i"  "i" 
# [10,] "j"  "j" 

另一个选项是separate

library(dplyr)
library(tidyr)
d %>% 
separate(x, into = c('x1', 'x2', 'x3')) %>% 
select(1:2) %>% 
as.matrix

相关内容

  • 没有找到相关文章

最新更新