I have a df like this
df <- data.frame (id = c(123,123,456), w1= c("abc","fgh","kit"), w2 = c("eat","drink","ty"))
id w1 w2
1 123 abc eat
2 123 fgh drink
3 456 kit ty
and a vector
vec <- c('value1', 'value2').
I would like to add these values to the df when there is a precise correspondance. The final df I'd like to obtain is like this:
id w1 w2 new_col
1 123 abc eat value1
2 123 abc eat value2
3 123 fgh drink no correspondance
4 456 kit ty no correspondance
I tried this code
for (i in 1:length(df$id)) { ## for iterating each row
if (df$w2[i] == 'eat') {
df$new_col[i] <- vec ### how to? Here I need to replace both 'value1' and 'value2' copying the row
}
}
Can someone suggest me something? Thanks in advance!
CodePudding user response:
Use tidyr
library:
> library(tidyr)
> df[1, 'new_col'] <- toString(vec)
> df %>% separate_rows(new_col)
# A tibble: 4 x 4
id w1 w2 new_col
<dbl> <chr> <chr> <chr>
1 123 abc eat value1
2 123 abc eat value2
3 123 fgh drink <NA>
4 456 kit ty <NA>
>
Edit:
> library(tidyr)
> df[1, 'new_col'] <- toString(vec)
> df %>% %>% filter(new_col %in% c('value1', 'value2')) %>% separate_rows(new_col) %>% bind_rows(filter(df, !new_col %in% c('value1', 'value2')))
# A tibble: 4 x 4
id w1 w2 new_col
<dbl> <chr> <chr> <chr>
1 123 abc eat value1
2 123 abc eat value2
3 123 fgh drink <NA>
4 456 kit ty <NA>
>
CodePudding user response:
You may add a list column to the dataframe and then use tidyr::unnest
to get them as separate rows.
inds <- df$w2 == "eat"
df$new_col[!inds] <- 'no correspondance'
df$new_col[inds] <- list(vec)
tidyr::unnest(df, new_col)
# id w1 w2 new_col
# <dbl> <chr> <chr> <chr>
#1 123 abc eat value1
#2 123 abc eat value2
#3 123 fgh drink no correspondance
#4 456 kit ty no correspondance