对于共享另一列中给出的相同 ID 的所有行,如何规范化数据框中的列值?
How can I normalize column values in a data frame for all rows that share the same ID given in another column?
我有一个看起来像这样的数据框
ID value
1 0.5
1 0.6
1 0.7
2 0.5
2 0.5
2 0.5
我想为具有相同 ID 的值添加一个标准化列,如下所示:norm = value/max(values with same ID)
ID value norm
1 0.5 0.5/0.7
1 0.6 0.6/0.7
1 0.7 1
2 0.5 1
2 0.3 0.3/0.5
2 0.5 1
有没有在 R 中不用先排序再循环的简单方法?
干杯
# Create an example data frame
dt <- read.csv(text = "ID, value
1, 0.5
1, 0.6
1, 0.7
2, 0.5
2, 0.5
2, 0.5")
# Load package
library(tidyverse)
# Create a new data frame with a column showing normalization
dt2 <- dt %>%
# Group the ID, make sure the following command works only in each group
group_by(ID) %>%
# Create the new column norm
# norm equals each value divided by the maximum value of each ID group
mutate(norm = value/max(value))
使用基本 R 工具的解决方案:
data$norm <- with(data, value / ave(value, ID, FUN = max))
函数 ave
非常有用,您可能需要阅读 ?ave
。
我们可以使用data.table
library(data.table)
setDT(dt)[, norm := value/max(value), ID]
我有一个看起来像这样的数据框
ID value
1 0.5
1 0.6
1 0.7
2 0.5
2 0.5
2 0.5
我想为具有相同 ID 的值添加一个标准化列,如下所示:norm = value/max(values with same ID)
ID value norm
1 0.5 0.5/0.7
1 0.6 0.6/0.7
1 0.7 1
2 0.5 1
2 0.3 0.3/0.5
2 0.5 1
有没有在 R 中不用先排序再循环的简单方法? 干杯
# Create an example data frame
dt <- read.csv(text = "ID, value
1, 0.5
1, 0.6
1, 0.7
2, 0.5
2, 0.5
2, 0.5")
# Load package
library(tidyverse)
# Create a new data frame with a column showing normalization
dt2 <- dt %>%
# Group the ID, make sure the following command works only in each group
group_by(ID) %>%
# Create the new column norm
# norm equals each value divided by the maximum value of each ID group
mutate(norm = value/max(value))
使用基本 R 工具的解决方案:
data$norm <- with(data, value / ave(value, ID, FUN = max))
函数 ave
非常有用,您可能需要阅读 ?ave
。
我们可以使用data.table
library(data.table)
setDT(dt)[, norm := value/max(value), ID]