0

Sorry everyone if this is already in another post, but I am totally new here and super green with R.

So what I am trying to achieve is that all values from a table with percentages above or equal to 15% should become a 1 and all values below 15% should become 0

I was thinking of gsub but can the "to be replaced" be a condition?

pick_it
  • 11
  • 1
  • Please add a small reproducible example. If you actually have percent signs, probably use `sub` to get rid of them so you can do a numeric conversion, then you can test them based on value. But we can't help you with code without seeing a data structure, preferably in a copy/pasteable format, e.g., `dput(your_table[1:3, ])` for the first 3 rows. – Gregor Thomas Jan 31 '22 at 16:19
  • If you need help making a reproducible example, [this FAQ has lots of r-specific tips](https://stackoverflow.com/q/5963269/903061) – Gregor Thomas Jan 31 '22 at 16:20

3 Answers3

1

Thanks all for trying to help i managed to solve my issues with this: Replacing values from a column using a condition in R

Surely yours would have helped too but I just could not use it because of my limitations. Thanks all for helping though!

pick_it
  • 11
  • 1
0

You could do:

library(dplyr)
data %>% 
   across(everything(), ~ case_when(.x >= 15 ~ 1, TRUE ~ 0))
DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
0

Using dplyr:

library(dplyr)

df <- data.frame(perc = c(0.1, 0.4, 0.13, 0.8))
df %>%
  mutate(perc = ifelse(perc < 0.15, 0, 1))
VvdL
  • 2,799
  • 1
  • 3
  • 14
  • df= name of the new object I am creating (I am adding it as a table to my data frame) data.frame = is the name of my data frame perc = is the name of my pre-existing table in the df with the percentages i get the following error: "Error: unexpected '=' in: " the last line of code – pick_it Jan 31 '22 at 17:40
  • No I think you are misunderstanding. I created my own data frame using df <- data.frame(c(0.1, 0.4, 0.13, 0.8)) to show how it works. If you already have a data frame you can skip this step and use your own data frame. Something like: library(dplyr) [your data frame] %>% mutate([your percentage column] = ifelse([your percentage column] < 0.15, 0, 1)) – VvdL Jan 31 '22 at 18:56
  • still Error: unexpected '=' in: mutate([your percentage column] = ifelse([your percentage column] < 0.15, 0, 1)) – pick_it Jan 31 '22 at 22:00
  • UPDATE: found a solution that worked for me here:https://stackoverflow.com/questions/13871614/replacing-values-from-a-column-using-a-condition-in-r - Surely yours would have helped but I just could not use it because of my limitations. Thanks for helping though! – pick_it Feb 01 '22 at 10:25