[英]Pairing ifelse with dplyr in R dataframe
在數據框df
中,我想分配一個條件,以便對於給定的月份和級別,如果值為 0 或 1,則分配“單獨”。 如果不指定“一起”。 最后,我想保留原始數據集行,但只添加將具有重復值的分配列。 這是我的嘗試,錯誤和所需的結果:
df <- data.frame(level = rep(c("1","2","3"), each = 5),
month = rep(c("J","J","A"), each = 5),
val = c(0,0,1,1,0,2,1,1,1,1,4,6,1,0,1))
df <- df %>%
dplyr::mutate(level, month, count)%>%
dplyr::group_by(month, level) %>%
dplyr::summarise(assign = ifelse(df$val %in% c(0,1), "alone", "together"))
Error:
mutate_cols()
中的錯誤:!mutate()
輸入問題..3
。 ℹ ..3..3 = count
。 ✖..3
必須是向量,而不是函數。
預期結果
level month val assign
1 1 J 0 alone
2 1 J 0 alone
3 1 J 1 alone
4 1 J 1 alone
5 1 J 0 alone
6 2 J 2 together
7 2 J 1 together
8 2 J 1 together
9 2 J 1 together
10 2 J 1 together
11 3 A 4 together
12 3 A 6 together
13 3 A 1 together
14 3 A 0 together
15 3 A 1 together
如果我沒有誤會您的意思,也許您可以嘗試以下方法:
data.frame(level = rep(c("1","2","3"), each = 5),
month = rep(c("J","J","A"), each = 5),
val = c(0,0,1,1,0,2,1,1,1,1,4,6,1,0,1)) %>%
mutate(assign = ifelse(level == 0 | month == 0 | level == 1 | month == 1,
yes = "alone", no = "together"))
這將為您提供以下輸出:
level month val assign
1 1 J 0 alone
2 1 J 0 alone
3 1 J 1 alone
4 1 J 1 alone
5 1 J 0 alone
6 2 J 2 together
7 2 J 1 together
8 2 J 1 together
9 2 J 1 together
10 2 J 1 together
11 3 A 4 together
12 3 A 6 together
13 3 A 1 together
14 3 A 0 together
15 3 A 1 together
如果那不是您所期望的,請告訴我:)
要使用新列返回原始數據框,您需要使用mutate
而不是summarise
。 在這里,我們可以在ifelse
語句中使用all
來限制只有那些特定的值,以便alone
賦值。 您也不需要代碼中的第一個mutate
語句。 也許,您想從原始數據框中使用select
。
df %>%
dplyr::group_by(month, level) %>%
dplyr::mutate(assign = ifelse(all(val %in% c(0, 1)), "alone", "together"))
輸出
level month val assign
<chr> <chr> <dbl> <chr>
1 1 J 0 alone
2 1 J 0 alone
3 1 J 1 alone
4 1 J 1 alone
5 1 J 0 alone
6 2 J 2 together
7 2 J 1 together
8 2 J 1 together
9 2 J 1 together
10 2 J 1 together
11 3 A 4 together
12 3 A 6 together
13 3 A 1 together
14 3 A 0 together
15 3 A 1 together
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.