GNicoletti
GNicoletti

Reputation: 204

Conditionally Concatenate String

I have a dataframe with these 5 columns

val1 val2 val3 val4 val5
1    0    3    0    5
0    0    0    0    5
1    2    0    0    0

etc

I was trying to create a new columns with a conditional concatenate (the result must not concatenate zeros)

val6
1,3,5
5
1,2

etc.

Any idea?

Upvotes: 1

Views: 2126

Answers (2)

akrun
akrun

Reputation: 887048

We can try with replace and gsub

gsub("NA\\s*|\\s*NA|NA+", "", do.call(paste,replace(df1, df1==0, NA)))
#[1] "1 3 5" "5"     "1 2"  

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388907

I think this is a duplicate. However, couldn't find one so answering.

We can use apply row-wise and remove the elements with value 0 and paste the remaining values seperated by a comma.

df$val6 <- apply(df, 1, function(x) paste0(x[x!=0], collapse = ","))
df

#  val1 val2 val3 val4 val5  val6
#1    1    0    3    0    5 1,3,5
#2    0    0    0    0    5     5
#3    1    2    0    0    0   1,2

Another option could be using by

df$val6 <- by(df, 1:nrow(df), function(x) paste0(x[x!=0], collapse = ","))

Upvotes: 2

Related Questions