![](/img/trans.png)
[英]Pasting values from a vector to a new column in a for loop with nested data
[英]Pasting several values from a vector into a dataframe column
我的 dataframe “測試”是這樣的:
a b c
d e f
我想將字符串添加到第一個 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
}
我想將行添加到測試 df 中,包括所有sb[i]
。
我試過rbind
,但沒有得到正確的結果
一個想法是根據您的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
數據
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.