[英]Pasting several values from a vector into a dataframe column
My dataframe "test" is like this:我的 dataframe “测试”是这样的:
a b c
d e f
I want to add strings to the 1st col so as to get this我想将字符串添加到第一个 col 以便得到这个
a__3 b c
a__23 b c
a__45 b c
...
sb <- c(3, 23, 45)
datalist <- ""
for (i in 1:length(sb)) {
new <- apply(test[,1],1,paste0,collapse=("__" sb[i]))
datalist[i] <- new
}
I want to add rows into test df including all sb[i]
.我想将行添加到测试 df 中,包括所有
sb[i]
。
I have tried rbind
, but does not get the correct result我试过
rbind
,但没有得到正确的结果
An idea is to replicate the rows based on the length of your sb
vector, do the paste
and filter to keep only the ones you are interested in, ie一个想法是根据您的
sb
向量的长度复制行,进行paste
和过滤以仅保留您感兴趣的行,即
d3 <- d2[rep(rownames(d2), length(sb)),]
d3$V1[d3$V1 == 'a'] <- paste0(d3$V1[d3$V1 == 'a'], '__', sb)
d3[grepl('a', d3$V1),]
# V1 V2 V3
#1 a__3 b c
#1.1 a__23 b c
#1.2 a__45 b c
DATA数据
dput(d2)
structure(list(V1 = c("a", "d"), V2 = c("b", "e"), V3 = c("c",
"f")), row.names = c(NA, -2L), class = "data.frame")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.