r - 根据另一列中的匹配复制值

时间:2015-11-30 12:37:07

标签: r

在此数据框中:

double[] ar = new double[]{0, 0.3, 0.7, 1.1, 1.5, 1.9, 2.3, 2.7, 3.1, 3.5, 3.9};
var odds = ar.Where((val, index) => index % 2 != 0);
var evens = ar.Where((val, index) => index % 2 == 0);

我想在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)) 替换df$condition的“已删除邮件”值。根据{{​​1}}中Fam和测试试验的匹配,df$Trial == "Test"的新值应为df$condition的副本df$condition

所以我的最终数据框应该是这样的

df$Trial == "Fam"

最终我想在原始数据框中为唯一ID执行此操作。所以我想我将不得不在df$Item左右的时间内应用该函数。

3 个答案:

答案 0 :(得分:6)

您可以 /** * @ORM\ManyToOne(targetEntity="Lead", inversedBy="leadPayment") */ private $lead; df上执行自我二进制加入,并使用{更新Trial != "Test"引用 {1}}包,例如

Condition

或者(对@docendos的一些修改)建议,只需

data.table

答案 1 :(得分:2)

以下是使用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 :(得分:2)

您也可以创建一个for循环并循环遍历所有需要更改的值。此设置可以轻松添加其他项目和/或稍后更改条件类型。

> 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"
>     }
> }