R 分离以将一列拆分为多列
我想根据字符串索引将R 分离以将一列拆分为多列,r,R,我想根据字符串索引将ID列拆分为3列(称为“A”、“B”、“C”)。第一列必须只报告项目1,第二列必须报告项目2:3,最后一列必须报告项目4:7 ID Data mw21e10 878 mw61e10 908 mw61e10 1073 我已经用下面所需的字符串位置定义了向量 a <- c(1,2,4) b <- c(1,3,7) a我们可以基于“a”、“b”向量使用substring,然后使用unne
ID
列拆分为3列(称为“A”、“B”、“C”)。第一列必须只报告项目1,第二列必须报告项目2:3,最后一列必须报告项目4:7
ID Data
mw21e10 878
mw61e10 908
mw61e10 1073
我已经用下面所需的字符串位置定义了向量
a <- c(1,2,4)
b <- c(1,3,7)
a我们可以基于“a”、“b”向量使用substring
,然后使用unnest\u wide
将列表
列更改为三列
library(dplyr)
library(tidyr)
mydata %>%
rowwise %>%
mutate(new = list(substring(ID, a, b))) %>%
ungroup %>%
unnest_wider(c(new), names_repair = ~c(names(mydata), 'A', 'B', 'C'))
-输出
# A tibble: 3 x 5
# ID Data A B C
# <chr> <int> <chr> <chr> <chr>
#1 mw21e10 878 m w2 1e10
#2 mw61e10 908 m w6 1e10
#3 mw61e10 1073 m w6 1e10
# ID A B C Data
#1 mw21e10 m w2 1e10 878
#2 mw61e10 m w6 1e10 908
#3 mw61e10 m w6 1e10 1073
-输出
# A tibble: 3 x 5
# ID Data A B C
# <chr> <int> <chr> <chr> <chr>
#1 mw21e10 878 m w2 1e10
#2 mw61e10 908 m w6 1e10
#3 mw61e10 1073 m w6 1e10
# ID A B C Data
#1 mw21e10 m w2 1e10 878
#2 mw61e10 m w6 1e10 908
#3 mw61e10 m w6 1e10 1073
或者使用base R
和Map
mydata[c('A', 'B', 'C')] <- Map(substring, mydata$ID,
MoreArgs = list(first = a, last = b))
mydata[c('A','B','c')]一个dplyr
和purrr
选项可以是:
df %>%
bind_cols(map2_dfc(.x = c(1,2,4),
.y = c(1,3,7),
~ df %>%
transmute(col = substr(ID, .x, .y))) %>%
set_names(c("A", "B", "C")))
ID Data A B C
1 mw21e10 878 m w2 1e10
2 mw61e10 908 m w6 1e10
3 mw61e10 1073 m w6 1e10
我已经安装了Tidyverse
,但是仍然无法安装unnest\u wide
功能found@Al14它来自tidyr
。您能否显示我使用的packageVersion('tidyr')
packageVersion('tidyr')
是0.8.3
@Al141.1.2
df %>%
bind_cols(map2_dfc(.x = c(1,2,4),
.y = c(1,3,7),
~ df %>%
transmute(col = substr(ID, .x, .y))) %>%
set_names(c("A", "B", "C")))
ID Data A B C
1 mw21e10 878 m w2 1e10
2 mw61e10 908 m w6 1e10
3 mw61e10 1073 m w6 1e10