I have a dataframe. and I want to add a newline "\n" with the words "?" or "①" as delimiters. ex) "?" -> "?\n" Typing "?\n" seems to cause a syntax error.
I have a dataframe :
sample :
aa <- data.frame(c('[1] aaaaa? ① bbbbb ② ccccc','[2] ccccc ① fffff ② ggggg'))
[1] aaaaa ① bbbbb ② ccccc
[2] ccccc ① fffff ② ggggg
result :
[1] aaaaaa? \n
① bbbbb \n
② ccccc
[2] cccccccc? \n
① fffff \n
② ggggg
CodePudding user response:
You have to use cat() instead of print() when you print to the console. For example:
aa <- data.frame(text = c('[1] aaaaa?\n① bbbbb\n② ccccc\n','[2] ccccc\n① fffff\n② ggggg\n'))
print(aa)
# text
# 1 [1] aaaaa?\n① bbbbb\n② ccccc\n
# 2 [2] ccccc\n① fffff\n② ggggg\n
cat(unlist(aa), sep="")
# [1] aaaaa?
# ① bbbbb
# ② ccccc
# [2] ccccc
# ① fffff
# ② ggggg
CodePudding user response:
If you are wanting to programmatically add the new lines, you can use gsub:
result = gsub(pattern = "([①②])" ,
replacement = "\n\\1", x = aa[[1]])
result
# [1] 1] "[1] aaaaa? \n① bbbbb \n② ccccc" "[2] ccccc \n① fffff \n② ggggg"
cat(result, sep = "\n")
# [1] aaaaa?
# ① bbbbb
# ② ccccc
# [2] ccccc
# ① fffff
# ② ggggg
As dcarlson explains, in the R console print will print the \n characters, cat will interpret them as line breaks.
CodePudding user response:
We could use separate_rows from tidyr package:
library(tidyr)
separate_rows(aa, text, sep = "\n")
text
<chr>
1 "[1] aaaaa?"
2 "<U 2460> bbbbb"
3 "<U 2461> ccccc"
4 ""
5 "[2] ccccc"
6 "<U 2460> fffff"
7 "<U 2461> ggggg"
