【问题标题】:How to split the script with | to the next line in r如何拆分脚本 |到 r 中的下一行
【发布时间】:2019-02-06 19:08:15
【问题描述】:

我想根据列中某些字符串的列表替换列值。但是列表太长了,我想切换到下一行。 但是,R 不会接受它。

####The test data file is data1
a <- runif (10)
b <- c("a;c", "a", "b", "c","a;b;c","a;d", "a;c", "a;b;c;d;e","e", "f")
c <- c(rep ("A-B", 4), rep("A_C", 6))
data1 <- data.frame (a, b, c)
data1 
####            a         b   c
####1  0.63360850       a;c A-B
####2  0.04681311         a A-B
####3  0.04743504         b A-B
####4  0.95342317         c A-B
####5  0.09054516     a;b;c A_C
####6  0.93139978       a;d A_C
####7  0.20558417       a;c A_C
####8  0.64131076 a;b;c;d;e A_C
####9  0.88136996         e A_C
####10 0.22000617         f A_C
list=c("a|b|c")
data1$b <- gsub(list, "[other]", data1$b)
####The ultimate goal example for the 1st line
####1  0.63360850       [other];[other] A-B
####But the list is actually too long, I have to move them into the next 
####line:
####E.g.:
list=c("a|
        b|
        c")

如何解决我的列表换行问题?我有不止 3 个字符串,而且每个字符串都非常长。 有人可以建议吗?提前非常感谢您!

【问题讨论】:

  • lst &lt;- paste(c("a|",\n"b|",\n"c"), collapse="")? (用实际的换行符代替我的\n 占位符)

标签: r


【解决方案1】:

您可以使用paste

my.list = paste(
  "a",
  "b",
  "c",
  sep ='|')
data1$b <- gsub(my.list, "[other]", data1$b)

或者另一种选择是在将列表定义为单个字符串后删除换行符:

my.list = 
"
a|
b|
c
"
my.list = gsub("\\n", "", my.list)

【讨论】:

  • 效果很好~非常感谢您的提示!
猜你喜欢
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
相关资源
最近更新 更多