我有这样的df:
df<- data.frame(result=c("p","p","p","d","d","p"),lep=c("A", "C", "E", "F","G", ""), psit= c("B", "D", "F", "G","H", ""))
如果符合以下要求,我想制作一个新的专栏paste
,将两个级别的不同因素粘贴在一起:1)result
必须= p
2)lep和psit列不是空白
输出应如下所示:
output<- data.frame(result=c("p","p","p","d","d", "p"),lep=c("A","C",
"E", "F","G", ""), psit= c("B", "D", "F", "G","H",""), paste=
c("A_B","C_D", "E_F", "", "",""))
我试过以下但没有成功。我相信这是因为我没有正确使用粘贴功能:
df<-df %>%
group_by(result) %>%
mutate(interact2=ifelse(psit==""| lep==""|result!="p", psit,
paste0(lep, psit, sep= "_")))
答案 0 :(得分:1)
正如@thelatemail所说,情况似乎有些混乱。此外,我认为您不需要group_by
。
library(dplyr)
df %>%
mutate(paste = ifelse(result == "p" & (lep != "" & psit != ""),
paste(lep, psit, sep = "_"), ""))
# result lep psit paste
#1 p A B A_B
#2 p C D C_D
#3 p E F E_F
#4 d F G
#5 d G H
#6 p
答案 1 :(得分:0)
以下是data.table
分配到位的选项
library(data.table)
setDT(df)[result == "p" & lep !="" & psit != "", paste := paste(lep, psit, sep="_")][]