R根据数据帧中的当前值替换值 [英] R replace value according to its current value in data frame

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

问题描述

我有一个关于ts1 [100,2000]的数据框架,如下所示:

I have a data frame that's about ts1[100, 2000] in dimension as follows:

> ts1[1:8, 1:6]
       DD LEVEL     X136747     X136749     X136752     X136753     ... ...
1 D04MX.x    LC        0.25        0.30       -0.01       -0.05
2 D08MX.x    LC        0.22        0.11        0.11        0.00
3 D15MX.x    LC        0.31        0.33       -0.23       -0.08
4 D29MX.x    LC        0.28        0.14       -0.28       -0.08
5 D04HX.x    SC        0.11       -0.26       -0.21       -0.33
6 D08HX.x    SC        0.25       -0.23       -0.07       -0.25
7 D15HX.x    SC        0.29        0.03       -0.05       -0.10
8 D29HX.x    SC        0.29        0.13       -0.09        0.02
... ...

我想替换所有的-0.1和0.1之间的值名为X ######(ts1 [3:ncol(ts1)])的列为0.我尝试了以下内容:

I would like to replace all the values that are between -0.1 and 0.1 under the columns named X###### (ts1[3:ncol(ts1)]) to be 0. I tried the following:

> ts1 <- ifelse(abs(ts1) < 1, 0, ts1)
Error in Math.data.frame(ts1) : 
  non-numeric variable in data frame: DDLEVEL
> ts1[which(abs(ts1) < 1)] <- 0
Error in Math.data.frame(ts1) : 
  non-numeric variable in data frame: DDLEVEL
> ts1[which(abs(is.numeric(ts1)) < 1)] <- 0
> ts1
  DD LEVEL X1367471_at X1367495_at X1367527_at X1367536_at
1  0    LC        0.25        0.30       -0.01       -0.05
2  0    LC        0.22        0.11        0.11        0.00
3  0    LC        0.31        0.33       -0.23       -0.08
... ...
> ts1 <- ts1[, lapply(.SD[3:ncol(ts1)], ifelse(abs(ts1) < 1, 0, ts1))]
Error in Math.data.frame(ts1) : 
  non-numeric variable in data frame: DDLEVEL

我做错了什么?我确实需要保留前两列。任何捷径?谢谢。

What am I doing wrong? I do need to retain the first two columns. Any shortcut? Thanks.

推荐答案

假设您的数据命名为 df

colsToEdit <- grepl("X", names(df))
df[, colsToEdit][abs(df[, colsToEdit]) <= 0.1] <- 0

给你:

 DD LEVEL X136747 X136749 X136752 X136753
1 D04MX.x    LC    0.25    0.30    0.00    0.00
2 D08MX.x    LC    0.22    0.11    0.11    0.00
3 D15MX.x    LC    0.31    0.33   -0.23    0.00
4 D29MX.x    LC    0.28    0.14   -0.28    0.00
5 D04HX.x    SC    0.11   -0.26   -0.21   -0.33
6 D08HX.x    SC    0.25   -0.23    0.00   -0.25
7 D15HX.x    SC    0.29    0.00    0.00    0.00
8 D29HX.x    SC    0.29    0.13    0.00    0.00

这篇关于R根据数据帧中的当前值替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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