我获得了具有可变数量列的数据帧,并且应该将行(粘贴)值连接成最终的列(摘要类型),如下所示:
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,
如何在姓氏后删除“,”?我可以将姓氏替换为“和”之前的“,”吗?此外,是否可以根据输入数据框中的列数进行调整?
提前致谢
答案 0 :(得分:0)
尝试使用以下代码:
apply(df,1,function(i){gsub("\\,"," and", toString(i[!is.na(i)]))})