[英]set to zero row values lover than rowmean
I have a dataframe that looks like this我有一个看起来像这样的数据框
v1 v2 v3 v4 v5
4 1 3 4 3
2 2 2 1 1
2 10 2 1 2
etc.
I want to transform the dataframe such that just raw values higher than raw mean are kept and the others are set to zero result would be:我想转换数据帧,以便只保留高于原始平均值的原始值,而其他值设置为零,结果将是:
v1 v2 v3 v4 v5
4 0 3 4 3
2 2 2 0 0
0 10 0 0 0
etc.
I tried something like this but it doesnt work (X is the dataframe):我尝试过这样的事情,但它不起作用(X 是数据框):
X<- X[sweep(X, 1, rowMeans(X) < 0)] <- 0
One option could be:一种选择可能是:
(df > rowMeans(df)) * df
v1 v2 v3 v4 v5
1 4 0 0 4 0
2 2 2 2 0 0
3 0 10 0 0 0
Using sweep
you could have done :使用sweep
你可以做到:
df[sweep(df, 1, rowMeans(df), `<`)] <- 0
df
# v1 v2 v3 v4 v5
#1 4 0 3 4 3
#2 2 2 2 0 0
#3 0 10 0 0 0
An option with replace
replace
选项
replace(X, X <= rowMeans(X), 0)
# v1 v2 v3 v4 v5
#1 4 0 0 4 0
#2 2 2 2 0 0
#3 0 10 0 0 0
X <- structure(list(v1 = c(4L, 2L, 2L), v2 = c(1L, 2L, 10L), v3 = c(3L,
2L, 2L), v4 = c(4L, 1L, 1L), v5 = c(3L, 1L, 2L)), class = "data.frame",
row.names = c(NA,
-3L))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.