简体   繁体   中英

Concatenate multiple cells in row into one cell with sep = “>”

I would like to concatenate the last three columns into a new one with a sep = ">" between all names. I have a df:

    1   2      3      4     5  
    70  54895  Den    Bas   Tom
    49  45975  John   River Max
    34  30295  Daen   Bob   Jimmy
    19  11995  Morgan Dylan Martin

Into

    1   2      3  
    70  54895  Den > Bas > Tom

Since some rows have multiple columns (198 at max), I can't just type out the column names "3", "4", "5", to concatenate those.

I tried to fix the problem by:

df$Names <- paste(df[, 3], sep = ">")

We can try using apply for one base R option:

df$Names <- apply(df[, 3:5], 1, function(x) {
                paste(ifelse(is.na(x), "-", x), collapse = " > ")
            })

The above would display - for those names which happen to be NA .

If instead you don't want to see NA values at all, then use:

df$Names <- apply(df[, 3:5], 1, function(x) {
                paste(x[!is.na(x)], collapse = " > ")
            })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM