r中的ifelse匹配向量 [英] ifelse matching vectors in r

查看:139
本文介绍了r中的ifelse匹配向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据框:

I have a dataframe that looks like this:

> df<-data.frame(A=c(NA,1,2,3,4),B=c(NA,5,2,6,4),C=c(NA,NA,2,NA,NA))
> df
   A  B  C
1 NA NA NA
2  1  5 NA
3  2  2  2
4  3  6 NA
5  4  4 NA

我想根据以下两个条件,使用此df的行值创建第4个D列: 1)如果行中的所有值都相同(不包括NA),则将相同值分配给列D; 2)如果值不同,则将A列中的值分配给D列。这将创建一个如下所示的向量和数据框:

I want to use the row values this df to create a 4th "D" column, based on the following 2 conditions: 1) if all of the values in the rows are the same (excluding NAs), then assign that "same" value to column D; 2) if the values are different, then assign the value in column A to column D. This would create a vector and dataframe that looks like this:

> df$D<-c(NA,1,2,3,4)
> df
   A  B  C  D
1 NA NA NA NA
2  1  5 NA  1
3  2  2  2  2
4  3  6 NA  3
5  4  4 NA  4


推荐答案

以下内容应该有效(修改后的示例建议由@flodel):

The following should work (with amended example suggested by @flodel):

df <- rbind(df,c(NA,5,5))

apply(df,1,function(x) {y<-x[!is.na(x)];if(length(unique(y))==1) unique(y) else x[1]})
 1  2  3  4  5  6 
NA  1  2  3  4  5 

这篇关于r中的ifelse匹配向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆