How to copy a column but only copy variables with "<" Symbol and change the rest to NA

Viewed 13

I have a dataset with concentrations. Some of them are labeled with a "<" symbol. I want to copy the column with the concentration but only the variables with "<" symbol in it. all others should be changed to "NA".

my code looks like this: raw_data$new_column <- ifelse(grepl("<", raw_data$Messwert, Value, "NA"))

obviously Value doesnt work. But i cant figure it out, I`m new to programming and would appreciate your help a lot. How should i solve this Problem?

my data set should look like this:

ID Concentration new_column
1 0.134 NA
2 <0.01 <0.01
3 0.32 NA
4 <0.0005 <0.0005
5 0.75 NA

Thank you very much.

2 Answers

We could use

raw_data$new_column <- ifelse(grepl("<", raw_data$Concentration),
     raw_data$Concentration, NA)

-output

> raw_data
  ID Concentration new_column
1  1         0.134       <NA>
2  2         <0.01      <0.01
3  3          0.32       <NA>
4  4       <0.0005    <0.0005
5  5          0.75       <NA>

data

raw_data <- structure(list(ID = 1:5, Concentration = c("0.134", "<0.01", 
"0.32", "<0.0005", "0.75")), class = "data.frame", row.names = c(NA, 
-5L))

Your ifelse needs a conditional argument first, try something like this

ifelse(grepl("<", raw_data$Concentration) == TRUE, raw_data$Concentration, "NA"))
Related