2

I have a data frame called 'Health_Difficulties' that looks like the one below. I would need to merge:

Health_Difficulties = data.frame(
X = c(2,2,1,2,2,1,2,2,2,2,2),
Y = c(2,1,2,1,2,1,2,2,2,1,2),
Z = c(2,2,2,1,2,2,2,1,2,2,1)
)

into a new column named W, in order to eliminate the 3 columns and only keep W. What I'm trying to accomplish with this merger is that if either X or Y or Z has a 1, it would record a 1 on the W column, else if neither of the three columns has a 1, it would record a 2.

I'm new in R and have checked out dplyr but so far no luck. Any help would be very appreciated!

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
dan19_dan
  • 21
  • 3
  • I'm removing the `[merge]` tag because that's usually associated with combining *datasets*, not *columns*. I'm removing the `[coalesce]` tag because that's usually associated with combining columns with missing/null cells. I'm not sure of a good tag to replace them, but I like @Jakub.Novotny's solution with `pmin()`. – wibeasley Jan 23 '20 at 21:23
  • @dan19_dan, check that your data frame is like what I have above? You should not use the <- assignment when creating a data.frame – StupidWolf Jan 23 '20 at 21:25

3 Answers3

2

This should achieve what you want.

library(tidyverse)

# creating you data
df <- data.frame(
  x = c(2,2,1,2,2,1,2,2,2,2,2),
  y = c(2,1,2,1,2,1,2,2,2,1,2),
  z = c(2,2,2,1,2,2,2,1,2,2,1)
)

# dplyr solution
df %>%
  mutate(w = pmin(x, y, z))

# base R solution
df$w <- do.call(pmin, df)
Jakub.Novotny
  • 2,912
  • 2
  • 6
  • 21
1

You just need to create a new vector or data.frame, if I get you correct.

So, you do

Health_Difficulties %>% 
mutate(W = 1+(rowSums(.==1)>0)) %>% 
select(W)
StupidWolf
  • 45,075
  • 17
  • 40
  • 72
0

This seemed to work for me:

library("tidyverse")

#Create Data
X <- c(2,2,1,2,2,1,2,2,2,2,2)
Y <- c(2,1,2,1,2,1,2,2,2,1,2)
Z <- c(2,2,2,1,2,2,2,1,2,2,1)

#Create dataframe
xyz_table <- as.data.frame(cbind(X,Y,Z))

#Use ifelse to alter your data
xyz_table <- xyz_table %>%
  mutate(W = ifelse (X == 1 | Y==1 | Z == 1,1,
         ifelse(X != 1 & Y != 1 & Z != 1, 2, 0)))

#Create dataframe with only column W
health_difficulties <- xyz_table %>% select (W)