Thank you for providing sample data. I see two issues with your code. First, your data frame subsetting call has incorrect syntax. Secondly, your data contains NA
values which are not the same thing as "n.a" strings. Operations on NA
values should be performed with special functions; in this case with is.na()
.
library(tibble)
df <- tribble(~`Turnover GBP 2019`, ~`Turnover GBP 2018`, ~`Turnover GBP 2017`,
63911000000, 57491000000, 55917000000,
29007000000, 28456000000, 26224000000,
17735000000, 17262000000, 16317000000,
15824000000, 15574000000, 15357000000,
NA, 15729000000, 16307000000,
NA, 10060000000, 8007000000,
4763100000, 4874800000, 4650200000,
4167400000, 4055500000, 4097300000,
NA, 3843000000, 3524000000,
NA, 3737600000, 3422300000)
df$`Turnover GBP 2019`[is.na(df$`Turnover GBP 2019`)] <- 0
print(df)
#> # A tibble: 10 x 3
#> `Turnover GBP 2019` `Turnover GBP 2018` `Turnover GBP 2017`
#> <dbl> <dbl> <dbl>
#> 1 63911000000 57491000000 55917000000
#> 2 29007000000 28456000000 26224000000
#> 3 17735000000 17262000000 16317000000
#> 4 15824000000 15574000000 15357000000
#> 5 0 15729000000 16307000000
#> 6 0 10060000000 8007000000
#> 7 4763100000 4874800000 4650200000
#> 8 4167400000 4055500000 4097300000
#> 9 0 3843000000 3524000000
#> 10 0 3737600000 3422300000
Created on 2020-03-05 by the reprex package (v0.3.0)
If you're open to using the tidyverse
, there is a dedicated function in tidyr
called replace_na()
for exactly this task.