简体   繁体   中英

Conditional past values in r

I get dataframes with a variable number of columns and should concatenate rows (paste) values together into a final colum (kind of a summary) as follows:

df <- data.frame(V1 = c("Adam", NA, "Tailor", "Daisy"),
                 V2 = c(NA, "Patrick", "Louis", NA), 
                 V3 = c(NA, "Ella", "Richard", "Laura"),
                 V4 = c("Norbert", NA, "Peter", NA),
                 stringsAsFactors = F)

final <- paste0(ifelse(is.na(df$V1), "" , paste0(df$V1,", ")), 
                ifelse(is.na(df$V2), "",  paste0(df$V2,", ")), 
                ifelse(is.na(df$V3), "",  paste0(df$V3,", ")), 
                ifelse(is.na(df$V4), "", df$V4))

> final
[1] "Adam, Norbert"                 "Patrick, Ella, "               "Tailor, Louis, Richard, Peter"
[4] "Daisy, Laura,

How can I remove "," after the last name? and can I replace the "," before the last name to "and"? Also, could the could be adapted according to the number of columns in the input dataframe?

Thanks in advance

尝试使用以下代码:

apply(df,1,function(i){gsub("\\,"," and", toString(i[!is.na(i)]))})

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