简体   繁体   中英

How to combine two or more variables into one in R?

Im currently trying to do a t-test with my data. I have three variables (or lets say groups). People that have cats or dogs or no pets. Now I want to form groups and put cat and dog-people into one group called "pets". And then im comparing this group with the "no-pet" group. How can i do this?

> mytable <- read.csv2("versuch.csv")
> mytable
  cats dogs none
1    3    1    3
2    5    2    2
3    3    6    5
4    8    8    9
5    5    5    8
6    6    9    2

I want it to look like this:

> mytable <- read.csv2("versuch.csv")
> mytable
  cats dogs none  pets
1    3    1    3  3
2    5    2    2  5
3    3    6    5  3
4    8    8    9  8
5    5    5    8  5
6    6    9    2  6
7                 1
8                 2
9                 6
10                8
...               ....
 

So basically I want to have one extra variable that consists both of the values of the cats and dog variable. Is there a possibility to achieve that?

We could use add_row from tibble package:

library(tidyverse)

df %>% 
  mutate(pets = cats) %>% 
  add_row(pets = df$dogs)

Output:

    cats  dogs  none  pets
   <dbl> <dbl> <dbl> <dbl>
 1     3     1     3     3
 2     5     2     2     5
 3     3     6     5     3
 4     8     8     9     8
 5     5     5     8     5
 6     6     9     2     6
 7    NA    NA    NA     1
 8    NA    NA    NA     2
 9    NA    NA    NA     6
10    NA    NA    NA     8
11    NA    NA    NA     5
12    NA    NA    NA     9

data:

df <- tibble::tribble(
~cats, ~dogs, ~none,
3, 1, 3, 
5, 2, 2, 
3, 6, 5, 
8, 8, 9,
5, 5, 8,
6, 9, 2)

You cannot have unequal number of rows for different columns in a dataframe. You can append NA 's to other column.

vec <- unlist(mytable[c('cats', 'dogs')], use.names = FALSE)
mytable <- cbind(mytable[1:length(vec), ], pets = vec)
rownames(mytable) <- NULL
mytable

#   cats dogs none pets
#1     3    1    3    3
#2     5    2    2    5
#3     3    6    5    3
#4     8    8    9    8
#5     5    5    8    5
#6     6    9    2    6
#7    NA   NA   NA    1
#8    NA   NA   NA    2
#9    NA   NA   NA    6
#10   NA   NA   NA    8
#11   NA   NA   NA    5
#12   NA   NA   NA    9

data

mytable <- structure(list(cats = c(3L, 5L, 3L, 8L, 5L, 6L), dogs = c(1L, 
2L, 6L, 8L, 5L, 9L), none = c(3L, 2L, 5L, 9L, 8L, 2L)), 
class = "data.frame", row.names = c(NA, -6L))

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