Reputation: 1
I want to create a new column that reports whether a separate column contains (=1) or does not contain (=0) data.
One way to do this is to create a column slugged with all 0 and then replace if the focal column is not NA - but this seems very sloppy to me. I'm guessing there is a one liner (if:else style) that is more elegant. I'm extremely new to R and have not programmed in many years.
Please advise.
Two liner:
data$New_Column <- 0
data$New_Column [!is.na(data$FocalColumn)] <- 1
Upvotes: 0
Views: 44
Reputation: 25736
You could use ifelse
:
data$NewColumn <- ifelse(is.na(data$FocalColumn), 0, 1)
Or convert the logical values to numeric:
data$NewColumn <- as.numeric(!is.na(data$FocalColumn))
Upvotes: 4