我有一个可重现的dat <- data.frame(IndID = factor(c(1,1,2,2,2,3,3)),
Order = c(1,2,1,2,3,1,2),
Media = factor(c("A", "B", "B","A","B","A", "A")))
dat
IndID Order Media
1 1 1 A
2 1 2 B
3 2 1 B
4 2 2 A
5 2 3 B
6 3 1 A
7 3 2 A
,其中有一个人重复采样。对于每个样品,我跟踪采样的顺序和使用的介质(A或B)。
dat$WantThis <- c("A1", "B1","B1", "A1","B2", "A1", "A2")
IndID Order Media WantThis
1 1 1 A A1
2 1 2 B B1
3 2 1 B B1
4 2 2 A A1
5 2 3 B B2
6 3 1 A A1
7 3 2 A A2
我想创建一个包含Media的新列和一个表示每个媒体级别中的采样顺序的数字。换句话说,IndID和Media进行分组,我想创建一个新的列来命令样本。对于每个人,如果在两个不同的媒体中只有两个样本(如IndID 1),则新值将是&#34; A1&#34;和&#34; B1&#34;。如果来自同一媒体的两个样本,则新值必须为&#34; B1&#34;和&#34; B2&#34;按照采样顺序之后的顺序。
鉴于以上数据,我正在尝试创建以下列
dplyr
我一直在尝试使用paste
软件包,但无法将第二个参数作为dat2 <- as.data.frame(dat %>% group_by(IndID, Media) %>% mutate(MediaOrder = paste0(Media, ???? )))
包含的内容连接起来。
DELIMITER $$
DROP TRIGGER IF EXISTS demo_bd $$
CREATE TRIGGER demo_bd BEFORE DELETE ON demo FOR EACH ROW
BEGIN
IF OLD.id = 1 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'This magical user cannot be deleted';
END IF;
END $$
DELIMITER ;
提前致谢。我欢迎任何建议。
答案 0 :(得分:2)
如果你使用分组的行号,它应该可以得到你想要的东西。
library(dplyr)
dat <- data.frame(IndID = factor(c(1,1,2,2,2,3,3)),
Order = c(1,2,1,2,3,1,2),
Media = factor(c("A", "B", "B","A","B","A", "A")))
res <- dat %>%
group_by(IndID, Media) %>%
mutate(count = row_number(),
WantThis = paste(Media,count,sep=""))
#Source: local data frame [7 x 5]
#Groups: IndID, Media [5]
#
# IndID Order Media count WantThis
# (fctr) (dbl) (fctr) (int) (chr)
#1 1 1 A 1 A1
#2 1 2 B 1 B1
#3 2 1 B 1 B1
#4 2 2 A 1 A1
#5 2 3 B 2 B2
#6 3 1 A 1 A1
#7 3 2 A 2 A2