在dplyr中有条件地改变数据
我试图通过基于标识符的划分来改变数据。 例如,我想在以下数据中变异在dplyr中有条件地改变数据,r,dplyr,R,Dplyr,我试图通过基于标识符的划分来改变数据。 例如,我想在以下数据中变异mass。如果它是深度10,我想除以2。如果深度是20,我想除以3 day year depth mass 1 2008 10 13 2 2008 10 15 1 2008 20 14 2 2008 20 12 1 2009 10 14 2 2009 10
mass
。如果它是深度10,我想除以2。如果深度是20,我想除以3
day year depth mass
1 2008 10 13
2 2008 10 15
1 2008 20 14
2 2008 20 12
1 2009 10 14
2 2009 10 16
1 2009 20 12
2 2009 20 18
分工导致:
day year depth mass
1 2008 10 6.5
1 2008 10 6.5
2 2008 10 7.5
2 2008 10 7.5
1 2008 20 4.6
1 2008 20 4.6
2 2008 20 4
2 2008 20 4
1 2009 10 7
1 2009 10 7
2 2009 10 8
2 2009 10 8
1 2009 20 4
1 2009 20 4
2 2009 20 6
2 2009 20 6
我正在用下面的方法尝试ifelse
,但得到一个错误“未使用的参数(c(13,15,14…)
用法:
就你而言:
ifelse(depth == 10, mass/2, ifelse(depth == 20, mass/3 , mass))
我发现在使用
ifelse
时有两个错误。如果有ifelse(depth==10)
,则只提供了一个需要三个参数的ifelse
参数。删除右括号,就有了一个好的开始
您的第二个错误是,如果第二个ifelse
条件解析为FALSE
,您没有给出任何指示。在下面的代码中,我已将NA
指定给该情况。但是,我不确定这是否是您想要的行为,因此您应该根据需要更改它
df%>%
group_by(day, year, depth) %>%
bind_rows(., .) %>%
mutate(mass = ifelse(test = (depth == 10),
yes = mass/2,
no = ifelse(test = (depth == 20),
yes = mass/3,
no = NA))) %>%
arrange(day, year, depth, mass)
模算子在这里工作得很好
df %>%
mutate(mass = mass *
as.integer(!(depth %% 10)) * 1 / 2 +
as.integer(!(depth %% 20)) * 1 / 3
) %>%
arrange(day, year, depth, mass)
# let underscore _ denote previous line result
# depth %% 10 ---> remainder left over after modulus division
# !(_) ---> coerce integer to logical and negate
# as.integer(_) ---> coerce back to integer for arithmetic operations
你应该提供一些背景知识来解释为什么你的解决方案可以帮助教育。好主意!@brittenbI只是想知道你为什么要将数据大小增加一倍。我是不是遗漏了什么?
df%>%
group_by(day, year, depth) %>%
bind_rows(., .) %>%
mutate(mass = ifelse(test = (depth == 10),
yes = mass/2,
no = ifelse(test = (depth == 20),
yes = mass/3,
no = NA))) %>%
arrange(day, year, depth, mass)
df %>%
mutate(mass = mass *
as.integer(!(depth %% 10)) * 1 / 2 +
as.integer(!(depth %% 20)) * 1 / 3
) %>%
arrange(day, year, depth, mass)
# let underscore _ denote previous line result
# depth %% 10 ---> remainder left over after modulus division
# !(_) ---> coerce integer to logical and negate
# as.integer(_) ---> coerce back to integer for arithmetic operations