Home > Mobile >  How can I extract hashtags from strings and export as a csv?
How can I extract hashtags from strings and export as a csv?

Time:11-15

I use the following function to extract hashtags from text data:

a <- c("#aaa", "#bbb", "#ccc")
hashtag_pat <- "#[a-zA-Z0-9_-ー\\.] "
hashtag <- str_extract_all(a, hashtag_pat)

Here's the output:

[[1]]
[1] "#aaa"

[[2]]
[1] "#bbb"

[[3]]
[1] "#ccc"

I can't, however, export this correctly as a csv. I need all these words in a single cell (separated by spaces). What is the best way to export this? The following is what 'write.csv' gives me. I appreciate if you could help fix this. enter image description here

CodePudding user response:

Update after clarification:

df <- data.frame(col1 = paste(a,collapse=" "))
df
            col1
1 #aaa #bbb #ccc

Are you looking for such a solution?

hashtag <- sub("^\\#", "", a)
write.csv(data.frame(t(unlist(hashtag))), "my_file.csv")

enter image description here

  • Related