retain - Retaining variable value in a dataframe in r -
i have dataframe
in r
id subgroup first.id var 103 17 true abc 103 17 false xyz 103 17 false def 103 17 false pqr 106 16 true abc 106 16 false pqr
first.id created identify first element in group(id). want create new variable should retain value in group. here, group use id variable. new dataframe
should this
id subgroup first.id var condition 103 17 true abc abc 103 17 false xyz abc or xyz 103 17 false def abc or xyz or def 103 17 false pqr abc or xyz or def or pqr 106 16 true abc abc 106 16 false pqr abc or pqr
df <- read.table(text="id subgroup first.id var 103 17 true abc 103 17 false xyz 103 17 false def 103 17 false pqr 106 16 true abc 106 16 false pqr", header=true) library(plyr) cumpaste <- function(x, sep) { sapply(seq_along(x), function(y,z,sep) paste(z[1:y], collapse=sep), z=x, sep=sep) } ddply(df, .(id), transform, condition=cumpaste(var, " or ")) # id subgroup first.id var condition # 1 103 17 true abc abc # 2 103 17 false xyz abc or xyz # 3 103 17 false def abc or xyz or def # 4 103 17 false pqr abc or xyz or def or pqr # 5 106 16 true abc abc # 6 106 16 false pqr abc or pqr
Comments
Post a Comment