R - copy value based on match in another column

In this data frame:

Item <- c("A","B","A","A","A","A","A","B")
Trial <- c("Fam","Fam","Test","Test","Test","Test","Test","Test")
Condition <-c("apple","cherry","Trash","Trash","Trash","Trash","Trash","Trash")
ID <- c(rep("01",8))


df <- data.frame(cbind(Item,Trial,Condition,ID))

I would like to replace the value "Trash" df$conditionwith df$Trial == "Test". The new value df$conditionshould be a copy df$conditionin df$Trial == "Fam"based on Fam and test tests in df$Item.

So my final data frame should look like this:

  Item Trial Condition ID
1    A   Fam     apple 01
2    B   Fam    cherry 01
3    A  Test     apple 01
4    A  Test     apple 01
5    A  Test     apple 01
6    A  Test     apple 01
7    A  Test     apple 01
8    B  Test    cherry 01

Ultimately, I would like to do this for a unique identifier in my original data frame. Therefore, I assume that I will have to apply the function to ddplyor later.

+4
source share
3 answers

df Trial != "Test" Condition data.table,

library(data.table) ## V 1.9.6+
setDT(df)[df[Trial != "Test"], Condition := i.Condition, on = c("Item", "ID")]
df
#    Item Trial Condition ID
# 1:    A   Fam     apple 01
# 2:    B   Fam    cherry 01
# 3:    A  Test     apple 01
# 4:    A  Test     apple 01
# 5:    A  Test     apple 01
# 6:    A  Test     apple 01
# 7:    A  Test     apple 01
# 8:    B  Test    cherry 01

( @docendos),

setDT(df)[, Condition := Condition[Trial != "Test"], by = .(Item, ID)]
+6

, dplyr

library(dplyr)
distinct(df) %>% 
    filter(Trial=='Fam') %>% 
    left_join(df, ., by = c('Item', 'ID')) %>% 
    mutate(Condition = ifelse(Condition.x=='Trash',
            as.character(Condition.y), as.character(Condition.x))) %>% 
    select(c(1,2,4,7))

@docendodiscimus

df %>% 
    group_by(ID, Item) %>%
    mutate(Condition = Condition[Condition != "Trash"])
+2

You can also just create a for loop and a loop through all the values ​​you need to change. This setting makes it easy to add other elements and / or change the condition type later.

> for(i in 1:nrow(df)) {
>     
>     if(df[i, 1] == "A") {
>         df2[i, 3] <- "apple"
>     }
>     else if(df[i, 1] == "B") {
>         df2[i, 3] <- "cherry"
>     }
> }
+1
source

Source: https://habr.com/ru/post/1617982/


All Articles