如何在R数据框中以其他列为条件创建列

时间:2019-12-26 11:06:43

标签: r

我正在尝试以当前列为条件创建一个新列。 条件是我正在使用grep函数的匹配条件。

数据像这样

            Keyword                         CPC     Impr   Clicks  
    singapore and malaysia tour packages    3.62    241    14     
    +singapore +holiday +packages           3.62    5      0              
    singapore tour packages from bangalore  3.62    201    12     
    "star cruise singapore"                 22.14   31     1    
    [singapore tourism]                     7.30    489    51

因此,第一列关键字具有“”,[],+符号。我想匹配这些符号以创建新列 分别使用词组匹配,完全匹配和广泛匹配等字符。

我正在使用grep函数来匹配符号。 请帮我一个函数,以根据匹配条件创建新列。

下面是我编写的一些代码(当然,这些代码会引发错误:()。请仔细阅读并提供建议。


pattern<- "[/+]"
pattern1<- "(\\[.*?\\])"
singapore$type<-ifelse(grep('"',singapore$Keyword),as.character("Phrase Match"),
                       ifelse(grep(pattern,singapore$Keyword),as.character("Broad Match"),
                              ifelse(grep(pattern1, singapore$Keyword), as.character("Exact Match"))))

错误消息

Error in `$<-.data.frame`(`*tmp*`, type, value = c("Phrase Match", "Phrase Match",  : 
  replacement has 71 rows, data has 113

func<-function(i)
for(i in 1:length(singapore$Keyword)){
    singapore$type<- i
    if(singapore[grep('"',singapore$Keyword),]){
        i==as.character("Phrase Match")
    }elseif(singapore[grep("[/+]",singapore$keyword),]){
        i==as.character("Broad Match")
    }else(singapore[grep("(\\[.*?\\])", singapore$Keyword),]){
        i==as.character("EXact Match")   
    }
}

错误消息

Error: unexpected symbol in:
"        i==as.character("Phrase Match")
    }elseif"
>         i==as.character("Broad Match")
Error: object 'i' not found
>     }else(singapore[grep("(\\[.*?\\])", singapore$Keyword),]){
Error: unexpected '}' in "    }"
>         i==as.character("EXact Match")   
Error: object 'i' not found
>     }
Error: unexpected '}' in "    }"
> }
Error: unexpected '}' in "}"

1 个答案:

答案 0 :(得分:0)

第一种方法

对于第一个问题,请使用grepl而不是grep,因为这将返回逻辑,即TRUE / FALSE语句。在上一次ifelse调用中,对于false返回什么没有参数,因此该函数不知道返回什么。 此外,as.character()语句不是必需的。

singapore$type<-ifelse(grepl('"',singapore$Keyword),"Phrase Match",
                       ifelse(grepl(pattern,singapore$Keyword),"Broad Match",
                              ifelse(grepl(pattern1, singapore$Keyword), "Exact Match", NA)))

我也不确定您的表情是否会达到预期的效果,但这是一个不同的问题。

第二种方法

您不需要for循环。在R中,通常最好先熟悉apply家庭。您的第一个版本应具有更好的可修复性。 循环和if语句存在大量构造错误。 例如,不必声明func<-function(i)

在第二行中,您将在循环的每次迭代中将i的值分配给名为type的新列。

if / ifelse构造中的每个条件语句中,您将传递grep的输出以选择数据框列。

通常,如果要进行布尔评估,则应使用grepl而不是grep。 我建议您阅读此https://www.w3schools.in/r/conditional-statements/