0

A seemingly simple R task has got me stumped… I have a Number field and a TrueFalse field in a data.frame as seen here.

#Make Data
TrueFalse <- rep(c("TRUE","TRUE", "FALSE"),10)
Number <- seq(1, length(TrueFalse),3)
Table <- as.data.frame(cbind(TrueFalse, Number))

look at the head()

head(Table)

I am trying to create a new column that contains values from the Numbers column if the TrueFalse field is TRUE. In a meta code:

For each row, NewField ==Number if TrueFalse = True, else nothing (ie. Leave as NA)

My working code is below. While searches have been productive, I am still missing a few steps. Thanks in advance for any help!

#for() loop using if()
NewField <- rep("NA", nrow(Table))
for (i in 1:nrow(NewField)){
    if(Table$TrueFalse[i] == "TRUE")
        {NewField[i] <- Table$Number[i]}
    }

2 Answers 2

2

First you don't want to cbind your columns before converting to a data frame. cbind will force the result to whatever data type is compatible with all your columns, so in this case, it'll turn your Number variable into character. Probably not what you want, if not now, then eventually.

Second, R has a logical data type, so you should use it. Especially if you have values called "TRUE" and "FALSE".

Thus:

TrueFalse <- rep(c(TRUE, TRUE, FALSE),10)
Table <- data.frame(TrueFalse, Number)

Table$NewField <- ifelse(Table$TrueFalse, Table$Number, -1)
Sign up to request clarification or add additional context in comments.

Comments

2

You can do this in one line. For example:

Table$NewField <- ifelse(Table$TrueFalse=="TRUE",Table$Number,-1)

Also, if you had used TRUE and FALSE instead of "TRUE" and "FALSE", you wouldn't need to use the equality test either.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.