-2

Recently, I started learning R. I would like to replace certain word in table by other word in the same table. For example, my table looks like

No. Fruits  Weight  Size
1   AB  200 L
2   AM  150 M
3   KD  50  S
4   KM  189 L
5   NA  260 L

I want to replace NA with word Fruits in this table. Can anyone help me?

mt1022
  • 16,834
  • 5
  • 48
  • 71
H. Suzuki
  • 1
  • 1
  • 2
  • It's a little dubious that your table actually looks like that; you have to work to get column names with spaces in them in R. Further, I'm not convinced it's a good idea to get rid of the `NA`s if they are, in fact, missing data. All that said, one option would be `library(dplyr); df %>% mutate(\`No. Fruits\` = coalesce(\`No. Fruits\`, 'Fruits'))` – alistaire May 06 '17 at 01:44

2 Answers2

1

The following creates data frame df with the sample data you provided:

df <- read.table(text = "No. Fruits  Weight  Size
1   AB  200 L
2   AM  150 M
3   KD  50  S
4   KM  189 L
5   NA  260 L", header=TRUE, stringsAsFactors=FALSE)

and the following will replace the NA with Fruits

df[is.na(df)] <- 'Fruits'
Imran Ali
  • 2,223
  • 2
  • 28
  • 41
1

That depends on whether that is the string "NA" or an actual NA (which, in R language, means "missing" or "error"). If it's the former, try

df$Fruits = gsub("NA", "Fruits", df$Fruits)

If it's the latter, try

df[is.na(df$Fruits),] = "Fruits"

Note that, if the Fruits column is a Factor which doesn't currently contain a "Fruits" entry, you might need to add this line at the top as well:

levels(df$Fruits) = c(levels(df$Fruits), "Fruits")
lebelinoz
  • 4,890
  • 10
  • 33
  • 56