多个条件然后创建新列
multiple condition then creating new column
我有一个包含两列的数据集,我需要创建第三列,其中包含第一列和第二列的条件。
set.seed(1)
x1=(sample(1:10, 100,replace=T))
y1=sample(seq(1,10,0.1),100,replace=T)
z=cbind(x1,y1)
unique(as.data.frame(z)$x1)
z%>%as.data.frame()%>%dplyr::filter(x1==3)
table(x1)
1 2 3 4 5 6 7 8 9 10
7 6 11 14 14 5 11 15 11 6
> z%>%as.data.frame()%>%dplyr::filter(x1==3)
x1 y1
1 3 6.9
2 3 9.5
3 3 10.0
4 3 5.6
5 3 4.1
6 3 2.5
7 3 5.3
8 3 9.5
9 3 5.5
10 3 8.9
11 3 1.2
例如,当我过滤 x==3 然后可以看到 y1 值时,我需要在第 11 行写 1,其余为 0。我需要在该列中找到最小值。我的原始数据集有 43545 行,但只有 638 个唯一数字,例如 x1。 table x1 显示 1 重复了 7 次,但在我的数据集中,有些频率为 1,有些频率为 100。我应该使用 case_when 但我如何检查每个 y1 以找到最小的 1 ?
如果我没理解错的话,您正在寻找对于每个 x1 值具有最小 y1 值的行
library(tidyverse)
z %>% as.data.frame() %>%
group_by(x1) %>%
arrange(y1) %>% # sort values by increasing order within each group
mutate(flag = ifelse(row_number()==1,1,0)) %>% # create flag for first row in group
ungroup()
我有一个包含两列的数据集,我需要创建第三列,其中包含第一列和第二列的条件。
set.seed(1)
x1=(sample(1:10, 100,replace=T))
y1=sample(seq(1,10,0.1),100,replace=T)
z=cbind(x1,y1)
unique(as.data.frame(z)$x1)
z%>%as.data.frame()%>%dplyr::filter(x1==3)
table(x1)
1 2 3 4 5 6 7 8 9 10
7 6 11 14 14 5 11 15 11 6
> z%>%as.data.frame()%>%dplyr::filter(x1==3)
x1 y1
1 3 6.9
2 3 9.5
3 3 10.0
4 3 5.6
5 3 4.1
6 3 2.5
7 3 5.3
8 3 9.5
9 3 5.5
10 3 8.9
11 3 1.2
例如,当我过滤 x==3 然后可以看到 y1 值时,我需要在第 11 行写 1,其余为 0。我需要在该列中找到最小值。我的原始数据集有 43545 行,但只有 638 个唯一数字,例如 x1。 table x1 显示 1 重复了 7 次,但在我的数据集中,有些频率为 1,有些频率为 100。我应该使用 case_when 但我如何检查每个 y1 以找到最小的 1 ?
如果我没理解错的话,您正在寻找对于每个 x1 值具有最小 y1 值的行
library(tidyverse)
z %>% as.data.frame() %>%
group_by(x1) %>%
arrange(y1) %>% # sort values by increasing order within each group
mutate(flag = ifelse(row_number()==1,1,0)) %>% # create flag for first row in group
ungroup()