Mahesh
Mahesh

Reputation: 11

Create a column based on multiple columns- in R

I am familiar with statistical packages including R but I kind of stopped working in R in between and recently started using it again.

I have simple questions and any help would be greatly appreciated it.

My question is: I want to create a variable by fulfilling in a condition based on multiple columns/variables. For instance, a new variable to code as "1" if there is no missing values in any one of the columns from 1 to 100 and to code as 0 if otherwise.

How could I possibly solve this in R or possible code suggestions?

Many thanks in advance.

Kind regards, Mahesh

Upvotes: 0

Views: 129

Answers (2)

akrun
akrun

Reputation: 887951

We can also do this without an ifelse

df$new.column <- with(df, +(is.na(a) & is.na(b)))

Upvotes: 1

MacOS
MacOS

Reputation: 1159

This is an example.

df <- data.frame(a = c(1, 2, 3, 4, 5, NA, NA), b=c(6, 7, 8, NA, 9, 10, NA))
df$new.column <- ifelse(is.na(df$a) & is.na(df$b), 1, 0)
df

HTH!

Upvotes: 0

Related Questions