【发布时间】:2020-09-14 09:24:10
【问题描述】:
我有一个数据框,其中包含城市中不同地区之间的距离。在根据条件进行分组时,某些位置会因此被其他位置“共享”,从而导致计算过程中的重复。因此,为了纠正重复,我试图计算一行的最小距离,并将该行中的所有其他值设为 0,这样我就可以只将行最小值纳入我的计算中。
Sample data:
> df <- data.frame(name = letters[1:3],
+ col1 = rnorm(3,10,1),
+ col2 = rnorm(3,10,1),
+ col3 = rnorm(3,10,1))
> df
name col1 col2 col3
1 a 9.994703 10.882758 9.005535
2 b 11.505343 9.613655 9.589866
3 c 11.713150 9.240391 9.788279
> df$min <- apply(df[,2:4],1,min)
> df
name col1 col2 col3 min
1 a 9.994703 10.882758 9.005535 9.005535
2 b 11.505343 9.613655 9.589866 9.589866
3 c 11.713150 9.240391 9.788279 9.240391
>
现在,我需要将非最小值的值设为 0。 预期输出:
> df
name col1 col2 col3 min
1 a 0 0 9.005535 9.005535
2 b 0 0 9.589866 9.589866
3 c 0 9.240391 0 9.240391
谁能告诉我怎么做。
【问题讨论】: