输入项

final_table =
  Chr     start       end   num seg.mean seg.mean.1 seg.mean.2
    1  68580000  68640000 A8430   0.7000     0.1440     0.1032
    1 115900000 116260000 B8430   0.0039     2.7202     2.7202
    1 173500000 173680000    C5  -1.7738    -0.0746    -0.2722

我如何制作一个新的data.frame,其中第5到7列的值设置为:
-1(如果值0-如果-0.679 如果值> 0.450,则+1
预期产量
Chr     start       end   num seg.mean seg.mean.1 seg.mean.2
  1  68580000  68640000 A8430        1          0          0
  1 115900000 116260000 B8430        0          1          1
  1 173500000 173680000    C5       -1          0          0

最佳答案

试试这个:

# read the data in
df <- read.table(header = TRUE, text="Chr     start       end        num    seg.mean    seg.mean.1   seg.mean.2
1   68580000    68640000    A8430    0.7000      0.1440     0.1032
1   115900000   116260000   B8430    0.0039      2.7202     2.7202
1   173500000   173680000   C5      -1.7738      -0.0746    -0.2722")

# get the column-names of the columns you wanna change
cols <- names(df[5:length(df)])
# set a function for the different values you want for the value-ranges
fun_cond <- function(x) {
    ifelse(x < -0.679 , -1, ifelse(
    x >= -0.679 & x <= 0.450, 0, 1))
}
# copy the data-frame so the old one doesnt get overwritten
new_df <- df

# work with data-table to apply the function to the columns
library(data.table)
setDT(new_df)[ , (cols) := lapply(.SD, fun_cond), .SDcols = cols]


输出:

   Chr     start       end   num seg.mean seg.mean.1 seg.mean.2
1:   1  68580000  68640000 A8430        1          0          0
2:   1 115900000 116260000 B8430        0          1          1
3:   1 173500000 173680000    C5       -1          0          0


同样的事情,不使用任何其他软件包:

cols <- names(df[5:length(df)])
fun_cond <- function(x) {
    ifelse(x < -0.679 , -1, ifelse(
        x >= -0.679 & x <= 0.450, 0, 1))
}

new_df <- df
new_df[5:length(df)] <- lapply(new_df[5:length(df)], fun_cond)

08-25 02:08