[英]Splitting column into two in R
我现在正在R中使用此当前数据帧,我的目标是在tidyr中使用单独的函数将songs_genre列分为两部分:
songs <- c("Wheel in the Sky", "Smooth Criminal", "Bloodstream", "New Kid in
Town", "You Belong with Me")
length <- c(211, 209, 299, 304, 232)
genre <- c("Rock", "Pop", "Pop", "Classic Rock", "Country Pop")
songList <- data.frame(songs, length, genre)
songList
songUnite <- unite(songList, "songs_genre", c("songs", "genre"), sep=".")
songUnite
但是,当我输入命令以分开时:
songSeparate <- separate(songUnite, col = songs_genre, into = c("songs", "genre"), sep=".")
songSeparate
出现此警告:
警告消息:预期2件。 在5行[1、2、3、4、5]中丢弃的其他碎片。
我已经在线检查了格式和变量是否都在正确的位置,但是似乎找不到我编写的错误。
我还包括图书馆(tidyr)
您已经“逃脱”了.
与sep = "\\\\."
。
.
是一个特殊的正则表达式字符,与任何字符匹配,除非转义。 最好使用_
分隔符来避免此问题。
您也可以使用package stringr
拆分一列:
require(stringr)
# data:
twowords <- c("hi there", "there how", "how are", "are you")
### split into two columns:
dat <- data.frame(
word1 = str_extract(twowords, "\\w.*(?=\\s)"), # regex says: match if you see space on the right
word2 = str_extract(twowords, "(?<=\\s)\\w.*") # regex says: match if you see space on the left
)
dat
word1 word2
1 hi there
2 there how
3 how are
4 are you
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.