简体   繁体   中英

Replacing the “x” in Data Frame Multiple Response Columns before Reshaping Using Tidyr

Below is a simple data frame.

Program <- c("A","B","C","D","E")
Apartment <- c("x","","","x","")
House <- c("x","","x","","")
Condo <- c("","x","","","x")
Cat <- c("x","","x","","")
Dog <- c("","x","","","")
Fish <- c("","x","","x","x")

DF1 <- data.frame(Program,Apartment,House,Condo,Cat,Dog,Fish)

Using this data frame, I would like to use Tidyr to create the table below. The table provides counts for the number of each pet by accommodation. So for those with an apartment, there is one instance of a cat, and one instance of a fish.

In order to accomplish this, I first have to replace the "x's" with the pet name for each column before melting the data. I would like to know how to do this across all columns in one line of code, or one function.

I'm also having trouble using Tidyr, or Reshape2, to create the table in the exact form below. ( The table below doesn't exactly line up, but each number should be below the pet name. So for the first row, the 1 should be under cat, the 0 under dog, and the 1 under fish, etc...)

      variable         Cat      Dog    Fish 
1     Apartment          1        0       1
2     House              2        0       0
3     Condo              0        1       2

We can try with dplyr/tidyr

library(dplyr)
library(tidyr)
DF1 %>% 
    gather(House, Val, Apartment:Condo) %>% 
    filter(Val!="") %>% 
    gather(Animals, Val2, Cat:Fish) %>%
    group_by(House, Animals) %>%
    summarise_each(funs(sum(.!='')), Val:Val2)  %>%
    spread(Animals, Val2) %>%
    select(-Val)   
#      House   Cat   Dog  Fish
#      <chr> <int> <int> <int>
#1 Apartment     1     0     1
#2     Condo     0     1     2
#3     House     2     0     0

Base version:

tmp <- data.frame(DF1[-1]=="x")
tmp <- data.frame(stack(tmp[1:3]), tmp[4:6])

aggregate(cbind(Cat,Dog,Fish) ~ ind, data=tmp, subset=tmp$values, FUN=sum)

#        ind Cat Dog Fish
#1 Apartment   1   0    1
#2     Condo   0   1    2
#3     House   2   0    0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM