如何合并两个或多个以“;”分隔的列一栏与R一起使用?谢谢
输出:
X Y XY
a;b;c; x;y;z; <b>ax</b></br><b>by</b></br><b>cz</b></br>
a2;b2;c2; x2;y2;z2; <b>a2x2</b></br><b>b2y2</b></br><b>c2z2</b></br>
a3;b3;c3; x3;y3;z3; <b>a3x3</b></br><b>b3y3</b></br><b>c3z3</b></br>
答案 0 :(得分:1)
我们可以使用strsplit
用;
然后用paste
分隔列
data.frame(XY = paste0("<b>", do.call(paste0,
lapply(df1, function(x) strsplit(x, ";")[[1]])), "</b></br>"))
# XY
#1 <b>ax</b></br>
#2 <b>by</b></br>
#3 <b>cz</b></br>
基于更新后的数据集
library(tidyverse)
map(df2, ~ strsplit(.x, ";")) %>%
transpose %>%
map_chr(reduce, ~
paste("<b>", .x, .y, "</b></br>", sep = "", collapse="")) %>%
bind_cols(df2, XY = .)
# X Y XY
#1 a;b;c; x;y;z; <b>ax</b></br><b>by</b></br><b>cz</b></br>
#2 a2;b2;c2; x2;y2;z2; <b>a2x2</b></br><b>b2y2</b></br><b>c2z2</b></br>
#3 a3;b3;c3; x3;y3;z3; <b>a3x3</b></br><b>b3y3</b></br><b>c3z3</b></br>
df2 <- structure(list(X = c("a;b;c;", "a2;b2;c2;", "a3;b3;c3;"), Y = c("x;y;z;",
"x2;y2;z2;", "x3;y3;z3;")), class = "data.frame", row.names = c(NA,
-3L))