Reputation: 133
Please kindly help with the issue why the code below produces vector ("1", "1") instead of expected ("1", "string") and how to fix it. Thank you.
data<-c("string")
data<-data.frame(lapply(data, type.convert), stringsAsFactors=FALSE)
colnames(data)<-c("Choice")
data<-rownames_to_column(data)
last_columns<-colnames(data)
columns_without_first<-last_columns[2:length(last_columns)]
converted_data<-as.character(unlist(data[1,]))
print(converted_data)
Upvotes: 0
Views: 40
Reputation: 887088
If we do the as.is
, it would be character
data <- c("string")
data <- data.frame(lapply(data, type.convert, as.is = TRUE), stringsAsFactors=FALSE)
colnames(data) <- "Choice"
str(data)
#'data.frame': 1 obs. of 1 variable:
#$ Choice: chr "string"
Or another option is retype
from hablar
library(hablar)
data <- c("string")
data.frame(data) %>%
retype
# A tibble: 1 x 1
# data
# <chr>
#1 string
Upvotes: 0
Reputation: 388982
That is because your Choice
argument is factor
. When you do
data<-c("string")
data<-data.frame(lapply(data, type.convert), stringsAsFactors=FALSE)
colnames(data)<-c("Choice")
str(data)
#'data.frame': 1 obs. of 1 variable:
# $ Choice: Factor w/ 1 level "string": 1
Instead do
data<-c("string")
data <- data.frame(Choice = data, stringsAsFactors=FALSE)
str(data)
#'data.frame': 1 obs. of 1 variable:
# $ Choice: chr "string"
So after you perform rest of the steps, you will get your expected output.
data<- tibble::rownames_to_column(data)
last_columns<-colnames(data)
columns_without_first<-last_columns[2:length(last_columns)]
converted_data<-as.character(unlist(data[1,]))
converted_data
#[1] "1" "string"
Upvotes: 3