Home > front end >  How to assign values for a column based on the values on anther column
How to assign values for a column based on the values on anther column

Time:06-06

I have the following data:

country        ccode
USA             2
Canada          20
Jordan          NA
India           750
China           NA
Armenia         371    
Pakistan        770

I want to manually enter the values for two NAs in the ccode column. For example, I want to say if the country variable is "china" then the ccode variable should be 710.

CodePudding user response:

Here is another option using fcase from data.table:

library(data.table)
dt <- as.data.table(df)

dt[ , ccode := fcase(
  !is.na(ccode), as.numeric(ccode),
  country == "China", 710,
  country == "Jordan", 3
)]

Output

    country ccode
1:      USA     2
2:   Canada    20
3:   Jordan     3
4:    India   750
5:    China   710
6:  Armenia   371
7: Pakistan   770

Another base R option is to use replace. If you have multiple rows for countries, then you will want to add & is.na(ccode) to the condition.

df$ccode <- replace(df$ccode, df$country == "China", 710)
df$ccode <- replace(df$ccode, df$country == "Jordan", 3)

Data

df <- structure(list(country = c("USA", "Canada", "Jordan", "India", 
"China", "Armenia", "Pakistan"), ccode = c(2L, 20L, NA, 750L, 
NA, 371L, 770L)), class = "data.frame", row.names = c(NA, -7L
))

CodePudding user response:

If your dataframe is called df, you can simply do something like

df$ccode[df$country=="China"] <- 710

CodePudding user response:

Try this

df$ccode[is.na(df$ccode) & df$country == "China"] <- 710

CodePudding user response:

You can use case_when from dplyr:

library(dplyr)

df %>% 
  mutate(ccode = case_when(country == "Jordan" ~ 123,
                           country == "China" ~ 710,
                           TRUE ~ as.double(ccode)))

This gives:

# A tibble: 7 x 2
  country  ccode
  <chr>    <dbl>
1 USA          2
2 Canada      20
3 Jordan     123
4 India      750
5 China      710
6 Armenia    371
7 Pakistan   770

Data:

df <- tibble::tribble(
    ~country, ~ccode,
       "USA",     2L,
    "Canada",    20L,
    "Jordan",     NA,
     "India",   750L,
     "China",     NA,
   "Armenia",   371L,
  "Pakistan",   770L
  )
  • Related