给出此数据框
column_1 column_2
A w,x
B z
C q,r,s
我想要的输出是
"Aw", "Ax", "Bz", "Cq", "Cr", "Cs"
我尝试过
paste0(df$column_1, strsplit(df$column_2, ","))
但是输出是
"Ac(\"w\", \"x\")" "Bz" "Cc(\"q\", \"r\", \"s\")"
答案 0 :(得分:2)
我们可以在{,上拆分column_2
,并使用column_1
将它们粘贴到mapply
unlist(mapply(paste0, df$column_1,strsplit(df$column_2, ",")))
#[1] "Aw" "Ax" "Bz" "Cq" "Cr" "Cs"
答案 1 :(得分:1)
我们可以通过rep
输出的lengths
的{{1}}中的list
来对'column_1'进行拼接,然后执行strsplit
paste
注意:上面是向量化方法,因为我们没有遍历 lst1 <- strsplit(df$column_2, ",")
paste0(rep(df$column_1, lengths(lst1)), unlist(lst1))
#[1] "Aw" "Ax" "Bz" "Cq" "Cr" "Cs"
或者使用list
从stack
然后是list
创建两列data.frame
paste
do.call(paste0, stack(setNames(lst1, df$column_1))[2:1])
#[1] "Aw" "Ax" "Bz" "Cq" "Cr" "Cs"
转换为两列data.frame方法可能比第一种方法效率低
或者使用stack
,用tidyverse
将'column_2'拆分为长格式,然后separate_rows
将两列并unite
拆分为pull
>
vector
OP方法中的问题基于这样一个事实,即library(tidyverse)
df %>%
separate_rows(column_2) %>%
unite(newcol, column_1, column_2, sep="") %>%
pull(newcol)
#[1] "Aw" "Ax" "Bz" "Cq" "Cr" "Cs"
输出是strsplit
中的list
个。我们需要一个函数将vector
的{{1}}(list
)或lapply/sapply/vapply
循环到unlist
的{{1}}'column_1'(在list
期间制作vector
)
replicating the
答案 2 :(得分:0)
这也可以使用下面的代码来实现。虽然不是很习惯
preferredWord