mercredi 11 août 2021

How to create an IF statement in R to trim the final character of cell

I have an issue where I concatenate two cells separated by a ", ". However, if the second cell in the concatenation is blank, the separator still shows.

I'm wondering if I can make an IF statement to output the result whereby

IF df[2,4] ENDS (", ") THEN {function to trim the comma off} ELSE df[2,4]

Say I have the following:

letters <- c("A", " ", "C")
numbers <- c(1, 2, 3)
names <- c("Matt", "Mark", "Luke")

df <- data.frame(letters, numbers, names)

df$concat <- ""

df[1,4] <- paste(df[1,3], df[1,1], sep = ", ")
df[2,4] <- paste(df[2,3], df[2,1], sep = ", ")
df[3,4] <- paste(df[3,3], df[3,1], sep = ", ")

Resulting in:

  letters numbers names  concat
1       A       1  Matt Matt, A
2               2  Mark Mark,  
3       C       3  Luke Luke, C     

So what I want to do is say IF any text in the concat column ends in , then omit JUST the comma

Aucun commentaire:

Enregistrer un commentaire