将多列合并为一列 [英] Coalescing many columns into one column
问题描述
如果我发布的问题与之前提出的问题类似,我深表歉意,但我意识到我原来的问题并不十分清楚。
I apologize if I post a similar question to one I asked earlier, but I realized that my original question wasn't very clear.
我有一个数据框五列和六行(实际上它们更多,只是为了简化问题):
I have a dataframe with five columns and 6 rows (actually they are many more, just trying to simplify matters):
One Two Three Four Five
Cat NA NA NA NA
NA Dog NA NA NA
NA NA NA Mouse NA
Cat NA Rat NA NA
Horse NA NA NA NA
NA NA NA NA NA
现在,我想将所有信息合并到一个新的单独列中(摘要 ),例如:
Now, I would like to coalesce all the information in a new single column ('Summary'), like this:
Summary
Cat
Dog
Mouse
Error
Horse
NA
请注意第四个摘要中报告的错误行,因为在合并过程中报告了两个不同的值。另外请注意,如果一行中仅包含NA,则应报告为 NA而不是 Error,我尝试查看其中的 coalesce函数的dplyr程序包,但实际上似乎并不能满足我的需求。
预先感谢。
Please note the 'Error' reported on the fourth Summary row, because two different values have been reported during the merging.Also please note that in case there are only NAs in a row, it should be reported 'NA' and not 'Error' I tried to look at the 'coalesce' function in the dplyr package, but it really desn't seem to do what I need. Thanks in advance.
推荐答案
一个 base R
选项可能是:
ifelse(rowSums(!is.na(df)) > 1, "Error", do.call(pmin, c(df, na.rm = TRUE)))
[1] "Cat" "Dog" "Mouse" "Error" "Horse" NA
这篇关于将多列合并为一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!