问题描述:

If I have a dataframe in R like this,

1 2 abc bh abd NA NA

2 3 abc NA NA NA NA

3 4 NA NA ad yu ae

...................

I want to get those values in columns 1 and 2 which have more than one value in the rest of the column. For example, here, 1 2 has 3 values and 3 4 has 3 values as well and 2 3 has only one value and rest are NA. So, I want 1 2 and 3 4. How can I do it in R?

Thanks!

网友答案:
x <- read.table(text="1 2 abc bh abd NA NA
2 3 abc NA NA NA NA 
3 4 NA  NA ad yu ae")

x[rowSums(!is.na(x[, -1:-2])) > 1, 1:2]
#  V1 V2
#1  1  2
#3  3  4

!is.na(x[, -1:-2]) returns a matrix of TRUE/FALSE values. rowSums converts TRUE values to 1 and FALSE values to 0 and sums them by row. Subset to only include rows where that is greater than 1, and return columns 1:2.

相关阅读:
Top