0

This is the simplified dataset I created to illustrate my question.

data

Hello all, I'm trying to reference a column in a dataframe Database. My goal is to be able to reference, say, the Weight column and from that populate the Risk and Overweight columns. Here is what I'm trying (along with other failed code):

ifelse(Database[,"Weight"] >190, Database$Risk="HIGH", Database$Risk="LOW")

Error: unexpected '=' in "ifelse(Database[,"Weight"] >190, Database$Risk="

I have also tried doing groups of code with the if() command.

if(Database$Weight > 190) {Database$Risk="HIGH"; Database$Overweight="YES"}

Error in if (Database$Weight > 190) { : 
missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In Ops.factor(Database$Weight, 190) : ‘>’ not meaningful for factors
2: In if (Database$Weight > 190) { :
the condition has length > 1 and only the first element will be used

...Which clearly I'm not doing correctly.

The ideal output of this code would resemble this:

The desired dataframe.

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • 2
    `Database$Risk=ifelse(Database$Weight >190, "HIGH", "LOW")` – HubertL Dec 19 '16 at 00:04
  • This worked! ... but I ran into a follow up error: In Ops.factor(Database$Weight, 190) : ‘>’ not meaningful for factors So I thought doing ` Database$Weight <- as.numeric(Database$Weight)` would fix this, but it made all of my weight values `c(1, 2, 3)`. How do I get my original weight values and make that a numeric column? – user5827247 Dec 19 '16 at 00:12
  • 2
    Don't post pictures of data; paste the result of `dput(my_data)`. [Info.](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#5963610) – alistaire Dec 19 '16 at 00:19
  • `Database$Risk=ifelse(as.double(as.character(Database$Weight)) >190, "HIGH", "LOW")` – HubertL Dec 19 '16 at 00:48
  • Try converting the `Weight` from factor to character like this `Database$Risk=ifelse(as.character(Database$Weight) >190, "HIGH", "LOW")` – Imran Ali Dec 19 '16 at 00:48

2 Answers2

0

We can avoid ifelse with in place assignment using data.table

library(data.table)
setDT(Database)[, Risk := "LOW"][Weight > 190, Risk := "HIGH"]
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Here is a dplyr solution. I have assumed Overweightis also classified based on Weight. You can change the condition if required.

library(dplyr)
df %>%
  mutate(Risk=ifelse(Weight>190,"HIGH","LOW"), 
         Overweight=ifelse(Weight>190,"YES","NO"))
Swapnil
  • 164
  • 8