Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having a data frame and from that, I want to change the value of the last column based on values of all previous columns.

The data set I am having:

id v1 v2 v3 wei

1  NA NA NA  1

2  1  1  2   2

3  1  1  NA  1

4  1  1  1   3

The data frame that I want as the output:

id v1 v2 v3 wei

1  NA NA NA  0

2  1  1  2   2

3  1  1  NA  1

4  1  1  1   3

Is this possible? I want to keep the same column called wei and just "update the value according to the condition.

1 Answer

0 votes
by (108k points)
edited by

You can achieve that using the tidyverse package with ifelse:

library(tidyverse)

df <- read.table(text="id v1 v2 v3 wei

1  NA NA NA  1

2  1  1  2   2

3  1  1  NA  1

4  1  1  1   3", header=T)

colnames(df)

#> [1] "id"  "v1"  "v2"  "v3"  "wei"

df

#>   id v1 v2 v3 wei

#> 1  1 NA NA NA   1

#> 2  2  1  1  2   2

#> 3  3  1  1 NA   1

#> 4  4  1  1  1   3

df %>% 

  mutate(wei = ifelse(is.na(v1) & is.na(v2) & is.na(v3), 0, wei))

#>   id v1 v2 v3 wei

#> 1  1 NA NA NA   0

#> 2  2  1  1  2   2

#> 3  3  1  1 NA   1

#> 4  4  1  1  1   3

You can achieve this in base R in a similar way:

# the same in base-R

df[is.na(df$v1)& is.na(df$v2)&is.na(df$v3),]$wei <- 0

df

#>   id v1 v2 v3 wei

#> 1  1 NA NA NA   0

#> 2  2  1  1  2   2

#> 3  3  1  1 NA   1

#> 4  4  1  1  1   3

If you are a beginner and want to know more about R then do refer to the R programming tutorial

Browse Categories

...