使用数据框中的特定标识符进行有条件突变
我有一个数据集,该数据集采用了类似的方法。
ID <- c(4,5,6,7,3,8,9)
quantity <- c(20,300, 350, 21, 44, 20, 230)
measurementvalue <- c("tin", "kg","kg","tin","tin","tin","kg")
kgs <- c(21,12, 30,23,33,11,24)
DF <- data.frame(ID, quantity, measurementvalue)
我使用条件突变的新列Totalkgs
的标准方法是以下代码。
DF <- DF %>%
mutate(totalkgs =
ifelse(quantity == "tin", quantity * 5,
ifelse(quantity =="kg", quantity*1, quantity)))
但是,该数据集在列数量
中具有错误的条目,因此我想对这些特定标识符执行划分。乘法和除法的所有最终值都应存储在列totalkgs
中。我该怎么做?
让我们假设带有错误数据的ID为3,5,9,7。我想将列数量中的值与10分开。
I have a dataset that employs a similar approach to this one.
ID <- c(4,5,6,7,3,8,9)
quantity <- c(20,300, 350, 21, 44, 20, 230)
measurementvalue <- c("tin", "kg","kg","tin","tin","tin","kg")
kgs <- c(21,12, 30,23,33,11,24)
DF <- data.frame(ID, quantity, measurementvalue)
My standard way of deriving a new column totalkgs
using conditional mutating is the code below.
DF <- DF %>%
mutate(totalkgs =
ifelse(quantity == "tin", quantity * 5,
ifelse(quantity =="kg", quantity*1, quantity)))
However, the dataset had erroneous entries in the column quantity
so I'd like to perform a division on those specific identifiers. All the final values of both the multiplication and division should be store in the column totalkgs
. How do I go about this?
Let's assume the id's with the error data are 3,5,9,7. and I'd like to divide the values found in the column quantity with 10.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
case_when
:在2022-07-05创建的(v2.0.1)
You could use
case_when
:Created on 2022-07-05 by the reprex package (v2.0.1)