0

I have 4 columns in a data frame, and based on the 2 columns, the 5th column of weights needs to be created. When the column value is NA, a 0 weight would be assigned.

Suppose I have this data frame in R called exp.

  from  to tel post
1  S01 S02 123  ABC
2  S02 S03 456 <NA>
3  S04 S05  NA  XYZ

I need to create the following weight column. Where weight = 10 * (tel) + 1* (post)

if the value is NA, then its zero

  from  to tel post weight
1  S01 S02 123  ABC  11
2  S02 S03 456 <NA>  10
3  S04 S05  NA  XYZ  1

Abikian
  • 49
  • 6

1 Answers1

0

You can do:

with(df, (10 * !is.na(tel)) + (1 * !is.na(post)))

[1] 11 10  1

Sample data:

df <- read.table(text = "  from  to tel post
1  S01 S02 123  ABC
2  S02 S03 456 <NA>
3  S04 S05  NA  XYZ",
                 header = TRUE,
                 stringsAsFactors = FALSE,
                 na.strings = c("NA", "<NA>"))
tmfmnk
  • 38,881
  • 4
  • 47
  • 67