user11740857
user11740857

Reputation: 480

Compare columns in R dataframe

Below is the dataframe. I am trying to compare 2 columns so that I get the output I require

asd <- data.frame(Ratings= c(1,2), Reviews = c(45,54))

Output I get

c("1" = asd$Reviews[asd$Ratings == 1], "2" = asd$Reviews[asd$Ratings == 2])
 1  2 
45 54

But if I do in a reverse way, I do not the expected output

c(asd$Reviews[asd$Ratings == 1] = 1, asd$Reviews[asd$Ratings == 2] = 2)

Expected output

45 54
1  2

Upvotes: 0

Views: 62

Answers (1)

akrun
akrun

Reputation: 887118

Use setNames

setNames(seq_along(asd$Ratings), asd$Reviews)
45 54 
 1  2 

Or use names<-

do.call(`names<-`, asd)
45 54 
 1  2 

which would also work in the new data

asd <- data.frame(Ratings= c("Yes","No"), Reviews = c(45,54))
do.call(`names<-`, asd)
   45    54 
"Yes"  "No" 

Or the same expression used in OP's post

setNames(c(1, 2), c(asd$Reviews[asd$Ratings == 1], asd$Reviews[asd$Ratings == 2]))
45 54 
 1  2 

Or more easily

library(tibble)
deframe(asd[2:1])

Or another option is := with dplyr::lst and then unlist

library(dplyr)
unlist(lst(!! glue::glue("{asd$Reviews[asd$Ratings == 1]}")  := 1, 
         !! glue::glue("{asd$Reviews[asd$Ratings == 2]}")  := 2))
45 54 
 1  2 

Upvotes: 1

Related Questions