简体   繁体   English

r中的条件过去值

[英]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)]))})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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