我有三个数据帧,每个数据帧都有一个rn_description
列和一个label
列。对于每个数据框,我想读取description
列中的文本,并且根据grepl
是否找到某些字符串,我想适当地标记label
列。
我尝试过
l=list(df1_wlabel= df1_wlabel,df2_wlabel=df2_wlabel,df3_wlabel=df3_wlabel)
l <- lapply(l ,
function(df){
df$label <- ifelse(grepl("email|e-mail", df$rn_description), "email", df$label)
df$label <- ifelse(grepl("phone|call|voicemail|conversation|convo",
df$rn_description), "phone", df$label)
df$label <- ifelse(grepl("text", df$rn_description), "text", df$label)
return(df)
}
)
我也尝试过for循环
for (i in 1:length(l)){
l[i]$label <- ifelse(grepl("email|e-mail", l[i]$rn_description), "email", l[i]$label)
l[i]$label <- ifelse(grepl("phone|call|voicemail|conversation|convo",
l[i]$rn_description), "phone", l[i]$label)
l[i]$label <- ifelse(grepl("text", l[i]$rn_description), "text", l[i]$label)
}
但是这些方法都不能正确更改label
列。仅显式地写出每个数据框的更改,如下所示:
df1_wlabel$label <- ifelse(grepl("email|e-mail", df1_wlabel$rn_description), "email", df1_wlabel$label)
df1_wlabel$label <- ifelse(grepl("phone|call|voicemail|conversation|convo", df1_wlabel$rn_description), "phone", df1_wlabel$label)
df1_wlabel$label <- ifelse(grepl("text", df1_wlabel$rn_description), "text", df1_wlabel$label)
#then do this again for each dataframe
为什么前两种方法不起作用,而最后一种方法起作用?