Reputation: 795
I have a df like so:
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", ""))
I would like to make a new column paste
that pastes two levels of different factors together, if it meets the following requirements: 1)result
must = p
2)The lep and psit columns are not blank
And the output should appear as follows:
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", "", "",""))
I have tried the following without success. I believe it is because I am not using the paste function properly:
df<-df %>%
group_by(result) %>%
mutate(interact2=ifelse(psit==""| lep==""|result!="p", psit,
paste0(lep, psit, sep= "_")))
Upvotes: 2
Views: 50
Reputation: 887108
Here is an option with data.table
to assign in place
library(data.table)
setDT(df)[result == "p" & lep !="" & psit != "", paste := paste(lep, psit, sep="_")][]
Upvotes: 0
Reputation: 388982
As @thelatemail suggested the condition seems to be mixed up. Also I don't think you need a group_by
here.
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
Upvotes: 1