在R中将列拆分为两个

时间:2018-11-30 00:10:03

标签: r tidyr

我现在正在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)

2 个答案:

答案 0 :(得分:2)

您已将docker swarm init docker stack deploy -c docker-compose.yml your-app “转义”了。

.是一个特殊的正则表达式字符,与任何字符匹配,除非转义。最好使用sep = "\\."之类的分隔符来避免此问题。

答案 1 :(得分:0)

您还可以使用软件包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
相关问题