在R中循环遍历Rumrame并向单元格添加文本

k2arahey  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(92)

以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


我已经能够将“Comment1\n\nComment2\nMeow”输出,但我很难将实际的换行符输出。
谢谢你,谢谢!

tpgth1q7

tpgth1q71#

如果我没理解错的话,

ToothGrowth$comment <- "Comment 1"
ToothGrowth$comment <- paste(ToothGrowth$comment, "\n", "Comment 2", "Meow", sep = "\n")

# Example of result: comment from first row
cat(ToothGrowth[1, ]$comment)
# Comment 1
#
#
# Comment 2
# Meow

字符串
在R语言中,如果你对每一行都做同样的事情,那么最好避免循环。向量运算通常要快得多。

相关问题