1

I'm still new in the R-Programming and am struggling with the following at the moment:

df <- tibble(
  'VPN'= c(01, 02, 03, 04, 05),
  '11'= c(1.12, 4.12,4.64, 0.72, 3.5), 
  '11x'= c(4, 6, 3,1, NA), 
  '12'= c(3.15, 4.68, 7.92, 5.83, 2.25),
  '12x' = c(5, 7, 2, 2, 6), 
  '13' = c(2.26, 3.73, 4.54, 6.55, 1.72), 
  '13x' = c(8,3,2,5,9)
)

I want to replace e.g. the values in the columns 11/11x for VPN 1 and the values in the columns 13/13x for VPN 5 by NA.

I wonder whether I can achieve this by indexing?

I've already tried..

df1 <- df[df$11] <- NA
df1 <- df(df$11x) <- NA 

..but this returns just a vector and not the original dataframe with changed values.

I'd be very happy to receive help. Thanks a lot !

Cath
  • 23,906
  • 5
  • 52
  • 86
JoB
  • 41
  • 2

2 Answers2

3

We can assign NA values for different columns based on VPN value. In base R,

df[df$VPN == 1, c("11", "11x")] <- NA
df[df$VPN == 5, c("13", "13x")] <- NA

# A tibble: 5 x 7
#    VPN  `11` `11x`  `12` `12x`  `13` `13x`
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1 NA       NA  3.15     5  2.26     8
#2     2  4.12     6  4.68     7  3.73     3
#3     3  4.64     3  7.92     2  4.54     2
#4     4  0.72     1  5.83     2  6.55     5
#5     5  3.5     NA  2.25     6 NA       NA

In dplyr, we can use mutate_at

library(dplyr)
df %>%
  mutate_at(vars(`11`, `11x`), ~replace(., VPN == 1, NA)) %>%
  mutate_at(vars(`13`, `13x`), ~replace(., VPN == 5, NA))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • thanks a lot, as I'm mostly working with the tidy verse package, I'm especially thankful for your second answer ! – JoB Sep 24 '19 at 11:04
1

You can try:

df$`11`[df$VPN == 1] = NA
df$`11x`[df$VPN == 1] = NA
df$`13`[df$VPN == 5] = NA
df$`13x`[df$VPN == 5] = NA
BetterCallMe
  • 636
  • 7
  • 15