R replace value according to its current value in

2019-08-15 02:38发布

问题:

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
... ...

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.

回答1:

Assuming your data is named df:

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

Gives you:

 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