【问题标题】:Concatenating strings from different rows in R连接来自R中不同行的字符串
【发布时间】:2014-04-14 00:50:30
【问题描述】:

我有一个看起来像

的 R 数据框
data.1       data.character
a            **str1**,str2,str2,str3,str4,str5,str6
b            str3,str4,str5
c            **str1**,str6

我目前正在使用grepl 来识别列 data.character 是否具有我的搜索字符串 "<str>",如果是,我希望将 data.1 中的所有行值连接成一个带有分隔符的字符串

例如。如果我使用grepl(str1,data.character),它将返回两行df$data.1,我想要一个像

这样的输出

a,c(data.character中包含str1的行)

我目前正在使用两个 for 循环,但我知道这不是一种有效的方法。我想知道是否有人可以提出一种更优雅、更省时的方法。

【问题讨论】:

  • 如果你的 data.frame 是 df 那么paste0(df$data.1[grep("str1", df$data.character)] ,collapse=",") 应该可以工作。
  • 谢谢!这完美无缺
  • 当你回答一个问题时,你应该发布一个答案,如果它有效,OP 应该接受它作为正确答案。这样,人们在查找类似内容时会看到针对该问题发布的正确答案。
  • @user20650 只是在 ping 你,以防 iraserd 的评论没有:-)。一定要继续发表您的评论作为答案。
  • @CarlWitthoft ,iraserd - 会的,干杯 - 很懒

标签: r grepl


【解决方案1】:

你就快到了——(现在是我啰嗦的回答)

# Data
df <- read.table(text="data.1       data.character
       a            **str1**,str2,str2,str3,str4,str5,str6
       b            str3,str4,str5
       c            **str1**,str6",header=T,stringsAsFactors=F)

匹配字符串

# In your question you used grepl which produces a logical vector (TRUE if
#string is present)

grepl("str1" , df$data.character)
#[1]  TRUE FALSE  TRUE

# In my comment I used grep which produces an positional index of the vector if
# string is present (this was due to me not reading your grepl properly rather 
# than because of any property)

grep("str1" , df$data.character)
# [1] 1 3

然后在 grep(或 grepl)产生的这些位置处对您想要的向量进行子集化

(s <- df$data.1[grepl("str1" , df$data.character)])
# [1] "a" "c"  first and third elements are selected

将它们一起粘贴成所需的格式(collapse 参数用于定义元素之间的分隔符)

paste(s,collapse=",")
# [1] "a,c"

更简洁

paste(df$data.1[grep("str1" , df$data.character)],collapse=",")


【讨论】:

  • 这很有帮助。谢谢!
猜你喜欢
  • 2017-08-19
  • 2011-02-18
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 2011-06-15
  • 1970-01-01
相关资源
最近更新 更多