使用R根据列填充行

时间:2017-09-20 19:35:39

标签: r

我有下表

    Code    Name    Class
    1       
    2       Monday  day
    5       green   color
    9       
    6       
    1       red     color
    1       
    2       
    9       Tuesday day
    6       
    5       

目标是根据填充行的“代码”列填充“名称”和“类”列。例如,第二行填充,代码为2.我想填充代码= 2的所有行,其中Name = Monday,Class = day。
我尝试使用来自tidyR的fill(),但这似乎需要有序数据。

有什么建议吗?肯定会感激任何帮助。

    structure(list(Code = c(1L, 2L, 5L, 9L, 6L, 1L, 1L, 2L, 9L, 6L, 
5L), Name = structure(c(1L, 3L, 2L, 1L, 1L, 4L, 1L, 1L, 5L, 1L, 
1L), .Label = c("", "green", "Monday", "red", "Tuesday"), class = "factor"), 
    Class = structure(c(1L, 3L, 2L, 1L, 1L, 2L, 1L, 1L, 3L, 1L, 
    1L), .Label = c("", "color", "day"), class = "factor")), .Names = c("Code", 
"Name", "Class"), class = "data.frame", row.names = c(NA, -11L
))

1 个答案:

答案 0 :(得分:3)

希望这有帮助!

library(dplyr)
final_df <- left_join(df, df[df$Name!='',], by='Code')[,c(1,4:5)]
colnames(final_df) <- colnames(df)
final_df