我试图根据一组条件将变量变异为0或1。然而,一旦满足了条件,我实际上只需要前几行(让我们基于小例子说第一行),而不是改变所有行。我正在努力在我的ifelse
语句中索引这些头寸。
我的dataframe看起来像这样:
df <-data.frame(individual = c("ind1", "ind1", "ind1", "ind1", "ind1",
"ind1", "ind1", "ind1", "ind1",
"ind1", "ind1", "ind1", "ind1", "ind1",
"ind1", "ind1", "ind1",
"ind2", "ind2", "ind2", "ind2", "ind2",
"ind2", "ind2", "ind2", "ind2",
"ind2", "ind2", "ind2", "ind2", "ind2",
"ind2", "ind2", "ind2"),
uniqueclass = c("migrate1", "migrate1",
"stop1", "stop1", "stop1",
"migrate2", "migrate2", "migrate2", "migrate2",
"stop2", "stop2",
"migrate3", "migrate3", "migrate3",
"winter1", "winter1", "winter1",
"migrate1", "migrate1",
"stop1", "stop1", "stop1",
"migrate2", "migrate2", "migrate2", "migrate2",
"stop2", "stop2",
"migrate3", "migrate3", "migrate3",
"winter1", "winter1", "winter1"),
class = c("migrate", "migrate", "stop", "stop", "stop",
"migrate", "migrate", "migrate", "migrate",
"stop", "stop", "migrate", "migrate", "migrate",
"winter", "winter", "winter",
"migrate", "migrate", "stop", "stop", "stop",
"migrate", "migrate", "migrate", "migrate",
"stop", "stop", "migrate", "migrate", "migrate",
"winter", "winter", "winter"),
mig_dur = c(10, 10, NA, NA, NA,
2, 2, 2, 2,
NA, NA, 4, 4, 4,
NA, NA, NA,
6, 6, NA, NA, NA,
3, 3, 3, 3,
NA, NA, 1, 1, 1,
NA, NA, NA)
)
字符串
我想做的是基于class == "migrate"
创建一个新列response
,其中migrate = 1,否则为0,* 但 * 仅选择前几行(在本例中,仅选择第一行)以基于唯一事件uniqueclass
变量创建1,其中只有每个唯一事件的第一个migrate行变为1,其他所有行均变为0。
我的代码看起来像这样--我在ifelse
语句中的位置索引方面遇到了问题:
df_new <- df %>% group_by(individual) %>%
mutate(response = ifelse(!is.na(mig_dur) & uniqueclass[1,], 1, 0)))
型
同样,我想要的输出是将uniqueclass == migratex
的第一行(即x = 1.n)变为1,而所有其他(包括其他迁移位置)以及所有stop和winter类变为0。
任何建议将不胜感激。尼克
1条答案
按热度按时间ovfsdjhp1#
我想你想要:
字符串
您可以通过更改
row_number <= n
来调整标记的行数。提供:
型