2017-10-17 53 views
1

我有一個data.frame,看起來像這樣:做一個因子變量了幾data.frame列

A <- data.frame(id = 1:5, col1 = c(0,1,1,0,0), col2 = c(2,0,0,0,0), col3 = c(0,0,0,3,3))

我如何做一個factor變出來的,所以它看起來就像這樣:

factor(c(2,1,1,3,3))

我知道如何使一個因素出一列,但不知道如何將它們合併在一起

回答

2

您可以使用rowSums

A <- data.frame(id = 1:5, col1 = c(0,1,1,0,0), col2 = c(2,0,0,0,0), col3 = c(0,0,0,3,3)) 
A$col4 <- as.factor(rowSums(A[,2:4])) 
str(A) 

> str(A) 
'data.frame': 5 obs. of 5 variables: 
    $ id : int 1 2 3 4 5 
$ col1: num 0 1 1 0 0 
$ col2: num 2 0 0 0 0 
$ col3: num 0 0 0 3 3 
$ col4: Factor w/ 3 levels "1","2","3": 2 1 1 3 3 
+0

謝謝!非常簡單。我應該自己想過'rowSums'。 –

2

可以全部爲零先轉換爲NA的,然後使用從dplyr​​3210到 「合併」 列到一個:

library(dplyr) 

A$col4 = A %>% 
    select(-id) %>% 
    mutate_all(funs(replace(., . == 0, NA))) %>% 
    {coalesce(!!! .)} %>% 
    as.factor() 

結果:

id col1 col2 col3 col4 
1 1 0 2 0 2 
2 2 1 0 0 1 
3 3 1 0 0 1 
4 4 0 0 3 3 
5 5 0 0 3 3 

> A$col4 
[1] 2 1 1 3 3 
Levels: 1 2 3 

注意:!!!表示法​​3210將參數拼接成圓點,所以相當於coalesce(A$col1, A$col2, A$col3)

+0

嗨!數據幀(* tmp *,col4,value = c(NA,1L,1L,NA,NA,: 替代品有15行,數據是錯誤的,但它給了我一個錯誤: '有5' –