我想基于行值的组合创建一个新的变量/列。我有超过7万个ID,每个ID有四行(每年一排,2013-2016年)。每年,它们的值为“ 0”或“ 1”。对于2013年,每个人都只能使用“ 0”,而对于2014-2016年,则只能具有全部“ 0”或全部具有“ 1”(因此有两种可能的组合:0000或0111;但在单独的行中)。
我想创建一个新变量,以指示ID属于哪个组。因此,如果四年中ID的组合为“ 0000”,那么我想在该新列中将所有年份的数字都设置为0。而且,如果ID的组合为“ 0111”,那么我希望该新列的所有年份都为1。这样,我可以为我的分析创建一个对照和一个治疗组。我的数据框包含其他变量,例如性别。
structure(list(Year = c(2013, 2014, 2015, 2016, 2013, 2014, 2015,
2016), Value = c(0, 0, 0, 0, 0, 1, 1, 1), ID = c(1, 1, 1, 1,
2, 2, 2, 2), Gender = c(0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA,
-8L), class = c("tbl_df", "tbl", "data.frame"))
tibble [8 x 4] (S3: tbl_df/tbl/data.frame)
$ Year : num [1:8] 2013 2014 2015 2016 2013 ...
$ Value : num [1:8] 0 0 0 0 0 1 1 1
$ ID : num [1:8] 1 1 1 1 2 2 2 2
$ Gender: num [1:8] 0 0 0 0 0 0 0 0
I've already tried these codes, but I couldn't make them work on my dataframe. - How do I create a new column based on multiple conditions from multiple columns? - How to create new variable based on a combination of values in other variables
希望有人有一些提示!
感谢您的帮助!
We can check for
any
1s (binary converted to logical withas.logical
) and coerce it back to binary with+
oras.integer