I was trying to generate a dialog box where a user can select elements to keep, however the item I want to keep is a character but it looks like R is giving them numeric values based on their alphabetical rank. Here's an example (I would prefer the list in the dialog box to be 1:Red, 2:Yellow, 3: Blue instead it's giving me 2, 3, 1):
library(dplyr)
library(tcltk)
library(utils)
x<-c(1,2,5)
y<-c(7,2.2,8)
c<-c("red", "yellow", "blue")
df<-as.data.frame(cbind(x,y,c),stringsasfactors=FALSE)
answer<-tk_select.list(df$c, preselect = NULL, multiple = TRUE,
title = "Select items to keep:")
selected_df<-filter(df, c %in% answer)
selected_df
We can create the data.frame
as
df <- data.frame(x, y, c, stringsAsFactors = FALSE)
With this, the output of selected_df
is
selected_df
# x y c
#1 1 7 red
NOTE: stringsasfactors
is not equal to stringsAsFactors
. So, the character
columns remain as factor
class
str(as.data.frame(cbind(x,y,c),stringsasfactors=FALSE) )
# 'data.frame': 3 obs. of 3 variables:
#$ x: Factor w/ 3 levels "1","2","5": 1 2 3
#$ y: Factor w/ 3 levels "2.2","7","8": 2 1 3
#$ c: Factor w/ 3 levels "blue","red","yellow": 2 3 1
Also, as.data.frame(cbind
, would have unnecessary issues as cbind
returns a matrix
and matrix
can have only a single class
i.e. all the columns are converted to character
class because the values in 'c' are character
. When we use as.data.frame
with stringsAsFactors = FALSE
, it does create character
class but numeric
columns should remain numeric