快速替换 R 中数据帧中的值 [英] Fast replacing values in dataframe in R
本文介绍了快速替换 R 中数据帧中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 150,000 行的数据框,其中 2,000 列包含值,有些是负数.我将这些负值替换为 0,但这样做非常慢(~60 分钟或更长时间).
I have a dataframe of 150,000 rows with 2,000 columns containing values, some being negatives. I am replacing those negative values by 0, but it is extremely slow to do so (~60min or more).
df[df <0] = 0
其中 df[,1441:1453]
看起来像(所有列/值都是数字):
where df[,1441:1453]
looks like (all columns/values numeric):
V1441 V1442 V1443 V1444 V1445 V1446 V1447 V1448 V1449 V1450 V1451 V1452 V1453
1 3 1 0 4 4 -2 0 3 12 5 17 34 27
2 0 1 0 7 0 0 0 1 0 0 0 0 0
3 0 2 0 1 2 3 6 1 2 1 -6 3 1
4 1 2 3 6 1 2 1 -6 3 1 -4 1 0
5 1 2 1 -6 3 1 -4 1 0 0 1 0 0
6 1 0 0 1 0 0 0 0 0 0 1 2 2
有没有办法加快这样的过程,例如我这样做的方式非常慢,而有更快的方法吗?谢谢.
Is there a way to speed up such process, eg the way I am doing it is utterly slow, and there is faster approach for this ? Thanks.
推荐答案
尝试将 df 转换为矩阵.
Try transforming your df to a matrix.
df <- data.frame(a=rnorm(1000),b=rnorm(1000))
m <- as.matrix(df)
m[m<0] <- 0
df <- as.data.frame(m)
这篇关于快速替换 R 中数据帧中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文