-2
$\begingroup$

I have a data frame

> head(custom.cn.data)
      Gene       Sample_name         CN
1: DDX11L1          F02         0.6788844
2: DDX11L1          C02        -0.9924524
3: DDX11L1          A07        -2.3833559
> 

I want to convert values in CN column < 0 to Del and >0 to Amp

But I am getting error

> a %>% mutate(q = replace(CN, which(CN<0), Del))
Error in replace(CN, which(CN < 0), Del) : object 'Del' not found

> a$CN <- replace(a$CN, which(a$CN < 0), Del)
Error in replace(a$CN, which(a$CN < 0), Del) : object 'Del' not found

Any help?

$\endgroup$
2
  • $\begingroup$ You are getting these errors because you did not use quotes before and after Del and R looks for an object called Del instead of using the string "Del". $\endgroup$
    – haci
    Jan 29, 2020 at 20:14
  • $\begingroup$ What happens to when CN is zero? $\endgroup$
    – zx8754
    Jan 30, 2020 at 9:32

3 Answers 3

6
$\begingroup$
custom.cn.data$new_column <- ifelse(custom.cn.data$CN < 0, "Del", "Amp")

In this scenario CN == 0 would be Amp

$\endgroup$
4
$\begingroup$

The following code would create a new column with the desired values, 0 values will have NA in this new column.

custom.cn.data[custom.cn.data$CN < 0, "CN_string"] <- "Del" 
custom.cn.data[custom.cn.data$CN > 0, "CN_string"] <- "Amp"
$\endgroup$
2
$\begingroup$

Try to stay within one package (paradigm) for one problem. This will make the code more readable, easier to debug.

At the moment you have data as a data.table object from data.table package, then trying to add a new column using mutate from dplyr package, and within mutate using base replace function.

Solutions:

data.table

# update by row index
custom.cn.data[ CN < 0, NewColumn := "Del" ]
custom.cn.data[ CN >= 0, NewColumn := "Amp" ]

or use ifelse

custom.cn.data[, NewColumn := ifelse(CN < 0, "Del", "Amp") ]

base

see @DavyCat's and @haci's answers.

dplyr

Note, this will change the data.table into data.frame.

# ifelse
custom.cn.data <- custom.cn.data %>%
  mutate(NewColumn = ifelse(CN < 0, "Del", "Amp"))

or use case_when

custom.cn.data <- custom.cn.data %>%
  mutate(NewColumn = case_when(
    CN < 0 ~ "Del",
    CN >= 0 ~ "Amp"))
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.