I have created a third column to concatenate V1 and V2 in this way:
dataframe = x
V1 V2
[1]
[2] 2A 3S
[3] 2A
x$V3<-paste(x$V1,x$V2,sep=",")
I obtain this
dataframe = x
V1 V2 V3
[1] "character(0),character(0)"
[2] 2A 3S 2A,3S
[3] 2A 2A,character(0)"
How do I remove the word character(0) and the other symbols like "," and " ?
CodePudding user response:
We can replace the character(0)
value with empty string when concatenating the two columns:
x$V3 <- gsub("^,|,$", "", paste(ifelse(identical(x$V1, character(0)), " ", x$V1),
ifelse(identical(x$V2, character(0)), " ", x$V2),
sep=","))
CodePudding user response:
To avoid getting unwanted symbols/values when combining columns, you can use tidyr function unite()
and get the desired result. I have attached an example below:
x[is.na(x)] <- "" # to remove NAs before combining
new_x <- unite(x, "V3", c("V1", "V2"), sep = " ", remove = FALSE)
If your initial table doesn't have the NAs, then you can use followed by unite()
funcyion:
x[x=="character(0)"] <- "NA" # to convert to NA
x[x=="character(0)"] <- "" # to instantly convert to empty string