r - Creating a conditional variable whose value=dataframe colnames -
i have dataset(df
),
id b c d e f 1 0 0 1 1 1 1 2 0 0 0 0 0 0 3 0 1 0 0 0 0
i trying write function give me names of columns have value 1 making dataset , have no thought start.
id b c d e f newcol 1 0 0 1 1 1 1 c,d,e,f 2 0 0 0 0 0 0 na 3 0 1 0 0 0 0 b
i appreciate help! thanks!!
here's approach
newdf <- transform(df, newcol=sapply(apply(df[, -1], 1, function(x) colnames(df[,-1])[x==1]), paste0, collapse=",")) levels(newdf$newcol)[levels(newdf$newcol)==""] <- "na" newdf # id b c d e f newcol # 1 1 0 0 1 1 1 1 c,d,e,f # 2 2 0 0 0 0 0 0 na # 3 3 0 1 0 0 0 0 b
r conditional
No comments:
Post a Comment