2

我有一个充满二进制变量的表,我想将其浓缩为分类变量。

非常简单地说,我有一个这样的数据框:

data <- data.frame(id=c(1,2,3,4,5,6,7,8,9), red=c("1","0","0","0","1","0","0","0","0"),blue=c("0","1","1","1","0","1","1","1","0"),yellow=c("0","0","0","0","0","0","0","0","1"))
data
  id   red   blue  yellow
1  1   1    0      0
2  2   0    1      0
3  3   0    1      0
4  4   0    1      0
5  5   1    0      0
6  6   0    1      0
7  7   0    1      0
8  8   0    1      0
9  9   0    0      1

我想回来的是:

  id   color 
1  1   red    
2  2   blue   
3  3   blue    
4  4   blue    
5  5   red    
6  6   blue    
7  7   blue    
8  8   blue    
9  9   yellow 

我希望有一个非常简单的答案。

4

2 回答 2

6

这是一个简单的基本 R 矢量化解决方案,使用max.col

cbind(data[1L], color = names(data[-1L])[max.col(data[-1L] == 1L)])
#   id  color
# 1  1    red
# 2  2   blue
# 3  3   blue
# 4  4   blue
# 5  5    red
# 6  6   blue
# 7  7   blue
# 8  8   blue
# 9  9 yellow
于 2015-03-24T08:33:27.590 回答
6

您可以通过使用列names和来获取值as.logical。但是,由于您的“二进制”列是因素,因此您需要再做几个箍:

> apply(data[-1], 1, function(x) names(x)[as.logical(as.numeric(as.character(x)))])
[1] "red"    "blue"   "blue"   "blue"   "red"    "blue"   "blue"   "blue"   "yellow"

将此与第一列 ( data[1]) 绑定,以获得您想要的输出。

cbind(data[1], 
      color = apply(data[-1], 1, 
                    function(x) names(x)[as.logical(as.numeric(
                      as.character(x)))]))
#   id  color
# 1  1    red
# 2  2   blue
# 3  3   blue
# 4  4   blue
# 5  5    red
# 6  6   blue
# 7  7   blue
# 8  8   blue
# 9  9 yellow

或者,您可以尝试以下方法:

data[-1] <- lapply(data[-1], function(x) as.numeric(as.character(x)))
temp <- subset(cbind(data[1], stack(data[-1])), values == 1, c("id", "ind"))
temp[order(temp$id), ]

或者,您可以使用“dplyr”和“tidyr”的组合,如下所示:

library(dplyr)
library(tidyr)

data %>%
  group_by(id) %>%
  mutate_each(funs(an = as.numeric(as.character(.)))) %>%
  gather(color, val, -id) %>%
  filter(val == 1) %>%
  select(-val) %>%
  arrange(id)
# Source: local data frame [9 x 2]
# 
#   id  color
# 1  1    red
# 2  2   blue
# 3  3   blue
# 4  4   blue
# 5  5    red
# 6  6   blue
# 7  7   blue
# 8  8   blue
# 9  9 yellow
于 2015-03-24T07:38:33.020 回答