how add variable dataset using aggregate , by commands? example, have:
num x1 1 1 1 0 2 0 2 0 and i'm looking create variable identify every variable num 1, example:
num x1 x2 1 1 1 1 0 1 2 0 0 2 0 0 or
num x1 x2 1 1 true 1 0 true 2 0 false 2 0 false i've tried use
df$x2 <- aggregate(df$x1, = list(df$num), fun = sum) but i'm getting error says replacement has different number of rows data. can help?
this can done grouping 'num' , checking if there any 1 element in 'x'1. ave base r convenient instead of aggregate
df1$x2 <- with(df1, ave(x1==1, num, fun = any)) df1$x2 #[1] 1 1 0 0 or using dplyr, group 'num' , create 'x2' checking if any 'x1' equal 1. logical vector if not wrapping as.integer convert binary
library(dplyr) df1 %>% group_by(num) %>% mutate(x2 = as.integer(any(x1==1)))
Comments
Post a Comment