我有一个简单的问题:假设我想根据另一列的值在一列上进行操作(在这种情况下乘以1000列Measure)(在这种情况下,当Unit等于L)。
有没有有效的方法?
我将报告一个简单的示例,但您不必专注于更改第二列值的名称。
输入:
a <- data.frame(Measure = c(10, 2000, 10000, 15, 40),
Unit = c("L","mL","mL","L","L"),
Price = c(100, 200, 500, 700, 900 ))
预期产出:
b <- data.frame(Measure = c(10000, 2000, 10000, 15000, 40000),
Unit = c("mL","mL","mL","mL","mL"),
Price = c(100, 200, 500, 700, 900 ))
答案 0 :(得分:2)
library(data.table)
DT = data.table(a)
DT[Unit == "L", `:=`(Measure = Measure * 1000, Unit = "mL")]
Measure Unit Price
1: 10000 mL 100
2: 2000 mL 200
3: 10000 mL 500
4: 15000 mL 700
5: 40000 mL 900
语法为DT[i, j]
:
i
j
:=
函数用于编辑列。
答案 1 :(得分:1)
使用以下代码,当Unit为“L”时,您只将Measure乘以1000;在所有其他情况下,仅返回Measure值而不进行乘法
a <- data.frame(Measure = c(10, 2000, 10000, 15, 40),
Unit = c("L","mL","mL","L","L"),
Price = c(100, 200, 500, 700, 900 ))
a$Measure <- ifelse(a$Unit == "L", a$Measure * 1000, a$Measure)
a
Measure Unit Price
1 10000 L 100
2 2000 mL 200
3 10000 mL 500
4 15000 L 700
5 40000 L 900
答案 2 :(得分:1)
与上面相同,只有tidyverse / dplyr方式:
> library(dplyr)
> a %>% mutate(Measure=ifelse(Unit=="mL",Measure,(Measure*1000)))
Measure Unit Price
1 10000 L 100
2 2000 mL 200
3 10000 mL 500
4 15000 L 700
5 40000 L 900