请教数据整形
frankzhang21 拜谢您的帮助!!
- 已编辑
借用上面的例子
library(tidyverse)
c1 <- c('a', 2015, 300)
c2 <- c('a', 2016, 400)
c3 <- c('b', 2015, 700)
c4 <- c('b', 2016, 600)
dt <- data.frame(rbind(c1, c2, c3, c4), stringsAsFactors = FALSE)
names(dt) <- c('name', 'date', 'amount')
new.dt <- dt %>%
group_by(name) %>%
filter(amount == max(amount)) %>%
mutate(merged = paste(date, amount, sep = "-")) %>%
ungroup()
去掉sep = "."
separate(data = ex, col =id, into = c("q", "w"))
即可
如果你一定要手动指定,
separate(data = ex, col =id, into = c("q", "w"),sep="\\.")
报错是因为你传进去的sep
会被当做一个正则表达式,.
在正则表达式里match任何字符(except new line)。
默认的sep
会match任何non-alphanumeric 的字符,绝大多数情况下使用默认的即可。
sep
Separator between columns.If character, is interpreted as a regular expression. The default value is a regular expression that matches any sequence of non-alphanumeric values.
frankzhang21 非常感谢您的热情帮助,原来是这么回事,感觉自己不适合学语言。大白这里再谢!!
frankzhang21 已修改。谢谢指正。
# 源数据
c1 <- c('a', 2015, 300)
c2 <- c('a', 2016, 400)
c3 <- c('b', 2015, 700)
c4 <- c('b', 2016, 600)
dt <- data.frame(rbind(c1, c2, c3, c4), stringsAsFactors = FALSE)
names(dt) <- c('name', 'date', 'amount')
library(dplyr)
library(tidyr)
dt %>%
group_by(name) %>%
filter(amount == max(amount)) %>%
unite("merged", date, amount, sep = "-") -> dt2
dt2
chuxinyuan 谢谢您的不吝赐教,拜谢!!