R Studio - 如何在数据框中随机位置的 string/vector 中间插入字符

R Studio - How to insert characters in the middle of a string/vector at random location in data frame

我正在尝试在数据帧中的矢量中间(不必在中间,但在中间)插入特殊字符 @、# 或 $。例如将@插入12345为12@345或123@45或1234@5.

这是我的:

> df <- data.frame(a=c(123,234,223214), b=c(78941014,0123,45645), 
c=c(41,54524,56465))
> df
       a        b     c
1    123 78941014    41
2    234      123 54524
3 223214    45645 56465

我想要这样的东西:

           a        b     c
1    12@3 7894@1014    41@
2    23@4      123 @ 54@524
3 22@3214    4564@5 56@465

我试过了 df8$a <- paste("@", df$a, sep="") 但它只是将 @ 添加到第一个字符。我希望它介于两者之间。

提前感谢您的帮助!

我想你可以这样做:

df <- data.frame(a=c(123,234,223214), b=c(78941014,0123,45645),c=c(41,54524,56465))
df2 <- as.data.frame(sapply(df, as.character))
df.output <- data.frame(a = character(), b = character(), c = character() ,stringsAsFactors=FALSE)


ncol <- ncol(df)
nrow <- nrow(df)

for (i in 1:ncol) {  
  for (j in 1:nrow) { 

    df.output[i,j]  <- sapply(Map(append, strsplit(as.character(df2[i,j]), ""), after = sample(1:nchar(df[i,j]), 1), "@"), paste, collapse = "")

  }  
}

df.output

        a         b      c
1    1@23 78941@014    41@
2    234@      123@ 5452@4
3 223@214    456@45 5646@5

您确实可以跳过 df.output 并直接使用 df2 更新值,但我想以清晰的方式展示解决方案。