快速替换R中数据帧中的值 [英] Fast replacing values in dataframe in R

查看:112
本文介绍了快速替换R中数据帧中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个150,000行的数据框,其中包含值为2,000列,有些是负数。
我将这些负值替换为0,但这样做非常慢(约60分钟或更长时间)。



df [df< 0] = 0



其中 df [,1441:1453] 所有栏/值数字):

  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

有没有办法加快这种过程,例如我这样做是非常缓慢的,而且有更快的方法呢?
谢谢。

解决方案

尝试将您的df转换为矩阵。

  df<  -  data.frame(a = rnorm(1000),b = rnorm(1000))
m< - as.matrix(df)
m [m <0] < - 0
df< - as.data.frame(m)


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

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.

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆