R 仅对重复的行求平均值,并替换定义列中的值

R 仅对重复的行求平均值,并替换定义列中的值,r,duplicates,aggregate,rename,mean,R,Duplicates,Aggregate,Rename,Mean,我有一个数据帧D: surname name salary Red A 1000 Green B 900 Green A 1100 Blue C 1000 Blue B 1000 Blue F 800 Violet F 1200 有些行在姓氏中没有复制,有些行是 我只需要将姓氏重复的行聚合为平均薪资值,并将名称更改为“X” 我使用dup

我有一个数据帧
D

surname   name   salary
Red        A      1000
Green      B       900
Green      A      1100
Blue       C      1000
Blue       B      1000
Blue       F       800
Violet     F      1200
有些行在
姓氏中没有复制,有些行是

我只需要将姓氏重复的行聚合为平均薪资值,并将名称更改为“X”

我使用
duplicated()
尝试了一些东西,但它保留了一个副本作为原始副本,并更改了其他副本

D$name<-replace(D$name,duplicated(D$surname),"X")
D$name我们可以使用

D$name <- replace(D$name,duplicated(D$surname)|duplicated(D$surname, 
          fromLast = TRUE),"X")
数据
D我们可以使用

D$name <- replace(D$name,duplicated(D$surname)|duplicated(D$surname, 
          fromLast = TRUE),"X")
数据
D谢谢akrun,但它不会聚合平均“工资”的行。谢谢akrun,我添加
D%distinct(姓氏,.keep_all=TRUE)
来删除重复项。我的预期输出是:
姓氏工资
红色A 1000
绿色X 1000
蓝色X 933.3
紫色F 1200
@Valdarn8在这种情况下,您可以将
mutate
更改为
summary
谢谢akrun,但它不会聚合平均“工资”的行。谢谢akrun,我添加
D%distinct(姓氏,.keep_all=TRUE)
删除重复项。我的预期输出是:
姓氏工资
红色A 1000
绿色X 1000
蓝色X 933.3
紫色F 1200
@Valdarn8在这种情况下,您可以将
mutate
更改为
summary
D <- structure(list(surname = c("Red", "Green", "Green", "Blue", "Blue", 
"Blue", "Violet"), name = c("A", "B", "A", "C", "B", "F", "F"
), salary = c(1000L, 900L, 1100L, 1000L, 1000L, 800L, 1200L)), class = "data.frame", row.names = c(NA, 
-7L))