我复制了一组数据,并且我想通过添加一个' A'来编辑我复制的行。到重复的行和' a'列#34; Code"下的原始行。示例如下。
可重现的数据框:
Date <- c("2016-01-02","2016-01-03","2016-01-04")
Data <- c("0",".2", ".1")
Code <- c("", "", "")
y <- data.frame(Date, Data, Code)
y<- y[rep(row.names(y),2),]
y$Date <- as.Date(y$Date, format='%Y-%m-%d')
y <- y[order(y$Date), ]
当前数据:
> y
Date Data Code
1 2016-01-02 0
1.1 2016-01-02 0
2 2016-01-03 .2
2.1 2016-01-03 .2
3 2016-01-04 .1
3.1 2016-01-04 .1
期望的结果:
> y
Date Data Code
1 2016-01-02 0 a
1.1 2016-01-02 0 A
2 2016-01-03 .2 a
2.1 2016-01-03 .2 A
3 2016-01-04 .1 a
3.1 2016-01-04 .1 A
答案 0 :(得分:2)
server.xml
返回带有FALSE的布尔向量,如果行是重复的,则返回TRUE。你可以按如下方式使用它:
duplicated(y)
输出:
y$Code = ifelse(duplicated(y),"A","a")
无需事先在 Date Data Code
1 2016-01-02 0 a
1.1 2016-01-02 0 A
2 2016-01-03 .2 a
2.1 2016-01-03 .2 A
3 2016-01-04 .1 a
3.1 2016-01-04 .1 A
中创建列,因此可能会成为:y <- data.frame(Date, Data, Code)
答案 1 :(得分:2)
或者您可以group
尝试dplyr
,以防每个日期中有两个以上的重复
y%>%group_by(Date)%>%dplyr::mutate(code=ifelse(row_number()==1,'a','A'))
#y%>%group_by(Date)%>%dplyr::mutate(code=ifelse(row_number()%%2==0,'A','a')) more than 2
# A tibble: 6 x 4
# Groups: Date [3]
Date Data Code code
<date> <fctr> <fctr> <chr>
1 2016-01-02 0 a
2 2016-01-02 0 A
3 2016-01-03 .2 a
4 2016-01-03 .2 A
5 2016-01-04 .1 a
6 2016-01-04 .1 A
例如:
y<- y[rep(row.names(y),3),]
y$Date <- as.Date(y$Date, format='%Y-%m-%d')
y <- y[order(y$Date), ]
y%>%group_by(Date)%>%dplyr::mutate(code=ifelse(row_number()%%2==0,'A','a')
# A tibble: 9 x 4
# Groups: Date [3]
Date Data Code code
<date> <fctr> <fctr> <chr>
1 2016-01-02 0 a
2 2016-01-02 0 A
3 2016-01-02 0 a
4 2016-01-03 .2 a
5 2016-01-03 .2 A
6 2016-01-03 .2 a
7 2016-01-04 .1 a
8 2016-01-04 .1 A
9 2016-01-04 .1 a
答案 2 :(得分:1)
带索引的简单基本R替代
y$Code <- c("a", "A")[duplicated(y) + 1]
返回
y
Date Data Code
1 2016-01-02 0 a
1.1 2016-01-02 0 A
2 2016-01-03 .2 a
2.1 2016-01-03 .2 A
3 2016-01-04 .1 a
3.1 2016-01-04 .1 A