Home > Mobile >  R updating dataframe elements given that a separate column element exists in another vector
R updating dataframe elements given that a separate column element exists in another vector

Time:06-30

I have a vector vec:

a<-c(4,2,9,2)

And a dataframe df:

   indx explore_ind
1     1        dark
2     2        dark
3     3        dark
4     4        dark
5     5        dark
6     6        dark
7     7        dark
8     8        dark
9     9        dark
10   10        dark
    
    df<-structure(list(indx = 1:10, explore_ind = c("dark", "dark", "dark", 
"dark", "dark", "dark", "dark", "dark", "dark", "dark")), row.names = c(NA, 
10L), class = "data.frame")

I would like to update any explore_ind from "dark" to "light" where indx exists in vec.

The result should be:

  indx explore_ind
1     1        dark
2     2        light
3     3        dark
4     4        light
5     5        dark
6     6        dark
7     7        dark
8     8        dark
9     9        light
10   10        dark

CodePudding user response:

ifelse option:

df$explore_ind <- ifelse(df$indx %in% a, "light", "dark")
df

Output:

   indx explore_ind
1     1        dark
2     2       light
3     3        dark
4     4       light
5     5        dark
6     6        dark
7     7        dark
8     8        dark
9     9       light
10   10        dark

CodePudding user response:

In base R

The square brackets allows us to subset by index when we are subseting a vector, which is what we have when we use $ on a column name

df$explore_ind[a] <- "light"

If indx isn't sorted you can use

df$explore_ind[df$indx %in% a] <- "light"

as suggested by @user2974951

CodePudding user response:

library(tidyverse)

df<-structure(list(indx = 1:10, explore_ind = c("dark", "dark", "dark", 
                                                "dark", "dark", "dark", "dark", "dark", "dark", "dark")), row.names = c(NA, 
                                                                                                                        10L), class = "data.frame") %>% 
  as_tibble()

a<-c(4,2,9,2)

df %>%  
  mutate(explore_ind = case_when(indx %in% a ~ "light", 
                                 TRUE ~ explore_ind))
#> # A tibble: 10 x 2
#>     indx explore_ind
#>    <int> <chr>      
#>  1     1 dark       
#>  2     2 light      
#>  3     3 dark       
#>  4     4 light      
#>  5     5 dark       
#>  6     6 dark       
#>  7     7 dark       
#>  8     8 dark       
#>  9     9 light      
#> 10    10 dark

Created on 2022-06-29 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related