1

This is my dataframe:

county          state   cases deaths  FIPS
Abbeville   South Carolina   4      0 45001
Acadia      Louisiana        9      1 22001
Accomack    Virginia         3      0 51001
New York C  New York         2      0 NA
Ada         Idaho           113     2 16001
Adair       Iowa             1      0 19001

I would like to manually put "55555" into the NA cell. My actual df is thousands of lines long and the row where the NA changes based on the day. I would like to add based on the county. Is there a way to say df[df$county == "New York C",] <- df$FIPS = "55555" or something like that? I don't want to insert based on the column or row number because they change.

M--
  • 25,431
  • 8
  • 61
  • 93
sofiajels
  • 33
  • 2

3 Answers3

1

This will put 55555 into the NA cells within column FIPS where country is New York C

df$FIPS[is.na(df$FIPS) & df$county == "New York C"] <- 55555

Output

df

#   county     state          cases deaths FIPS 
# 1 Abbeville  South Carolina     4      0 45001
# 2 Acadia     Louisiana          9      1 22001
# 3 Accomack   Virginia           3      0 51001
# 4 New York C New York           2      0 55555
# 5 Ada        Idaho            113      2 16001
# 6 Adair      Iowa               1      0 19001
# 7 New York C New York           1      0 18000

Data

df

#   county     state          cases deaths  FIPS
# 1 Abbeville  South Carolina     4      0 45001
# 2 Acadia     Louisiana          9      1 22001
# 3 Accomack   Virginia           3      0 51001
# 4 New York C New York           2      0    NA
# 5 Ada        Idaho            113      2 16001
# 6 Adair      Iowa               1      0 19001
# 7 New York C New York           1      0 18000
nurandi
  • 1,588
  • 1
  • 11
  • 20
0

You could use & (and) to substitute de df$FIPS entries that meet the two desired conditions.

df$FIPS[is.na(df$FIPS) & df$state=="New York"]<-5555
0

If you want to change values based on multiple conditions, I'd go with dplyr::mutate().

library(dplyr)
df <- df %>%
  mutate(FIPS = ifelse(is.na(FIPS) & county == "New York C", 55555, FIPS))
neilfws
  • 32,751
  • 5
  • 50
  • 63