循环数据框并向 R 中的单元格添加文本

问题描述 投票:0回答:1

以 R 中的 ToothGrowth 数据集为例,我使用

ToothGrowth$comment <- "Comment 1"
创建了以下格式的评论列:

   len supp dose comment
1  4.2   VC  0.5  Comment 1
2 11.5   VC  0.5  Comment 1
3  7.3   VC  0.5  Comment 1

我想循环遍历每一行并添加更多注释,以便最终的数据框看起来像这样:

   len supp dose comment
1  4.2   VC  0.5  Comment 1
                  
                  Comment 2
                  Meow
2 11.5   VC  0.5  Comment 1

                  Comment 2
                  Meow

3  7.3   VC  0.5  Comment 1
                  
                  Comment 2
                  Meow

到目前为止,我有这三件事:

for i in 1:nrow(ToothGrowth):
  newcom <- paste("Comment 2", "Meow", sep="\n")
  addnewcom <- paste(ToothGrowth$comment[i], newcom, sep="\n", col="\n")
  ToothGrowth$comment[i] <- addnewcom

for i in 1:nrow(ToothGrowth):
  newcom <- paste("Comment 2", "Meow", sep="\n")
  addnewcom <- paste(ToothGrowth$comment[i], cat(newcom[1]), sep="\n", col="\n")
  ToothGrowth$comment[i] <- cat(addnewcom[1])

for i in 1:nrow(ToothGrowth):
  newcom <- capture.outcome(cat(paste("Comment 2", "Meow", sep="\n")))
  addnewcom <- capture.outcome(cat(paste(ToothGrowth$comment[i], newcom, sep="\n", col="\n")))  
  ToothGrowth$comment[i] <- addnewcom

谢谢!

r dataframe variable-assignment line-breaks string-concatenation
1个回答
0
投票

如果我正确理解你的意图的话,那就是

ToothGrowth$comment <- "Comment 1"
ToothGrowth$comment <- paste(ToothGrowth$comment, "\n", "Comment 2", "Meow", sep = "\n")
© www.soinside.com 2019 - 2024. All rights reserved.