给定某些列条件,R中的哪个函数将添加新行?

时间:2019-05-30 22:26:15

标签: nested row

我有兴趣为那些仅在数据集中出现一次或两次的ID(Id = 3370和3360)创建新的观察值。因此,给定n = 1或n = 2,我需要一个函数来创建新行。

以下是数据:

df <- data.frame(Id = c(6431, 6431, 6431, 6431, 3066, 3066, 3066, 3371, 3371, 3371, 3370, 3360, 3360), Order = c(1, 2, 3, 4, 3, 2, 1, 2, 1, 3, 1, 1, 2), Service = c("C", "E", "F", "C", "C", "E", "F", "C", "E", "F", "C", "E", "C"), n=c(4,4,4,4,3,3,3,3,3,3,1,2,2))

> df
     Id Order Service n
1  6431     1       C 4
2  6431     2       E 4
3  6431     3       F 4
4  6431     4       C 4
5  3066     3       C 3
6  3066     2       E 3
7  3066     1       F 3
8  3371     2       C 3
9  3371     1       E 3
10 3371     3       F 3
11 3370     1       C 1
12 3360     1       E 2
13 3360     2       C 2

下面是我希望数据看起来的样子(对于显示一次或两次的每个ID,S *已附加到数据帧中)。

dfS=data.frame(Id=c(6431,6431,6431,6431,3066,3066, 3066,3371,3371,3371,3370,3370,3360,3360,3360), Order=c(1,2,3,4,3,2,1,2,1,3,1,2,1,2,3), Service=c("C","E","F","C", "C","E","F","C", "E","F","C","S*","E","C", "S*"))

 > dfS
     Id Order Service
1  6431     1       C
2  6431     2       E
3  6431     3       F
4  6431     4       C
5  3066     3       C
6  3066     2       E
7  3066     1       F
8  3371     2       C
9  3371     1       E
10 3371     3       F
11 3370     1       C
12 3370     2      S*
13 3360     1       E
14 3360     2       C
15 3360     3      S*

在此使用什么适当的功能?

0 个答案:

没有答案