Ujjwal
Ujjwal

Reputation: 3168

Remove quotes from paste() output in R while preserving the class

I have a dataframe "c1" with one column as "region".

sum(is.na(c1$region))
[1] 2

class(c1$region)
[1] "factor"

However, when I use paste()

f1<-paste("c1","$","region",sep="")

> f1
[1] "c1$region"

> sum(is.na(f1))
[1] 0

I tried as.name(f1) and as.symbol(f1). Both convert f1 to the "name" class. noquote(f1) converts the char[1] element to the "noquote" class.

> f2<-as.name(f1)

> f2
`c1$region`

> sum(is.na(f2))
[1] 0
Warning message:
In is.na(f2) : is.na() applied to non-(list or vector) of type 'symbol'

> class(f2)
[1] "name"

I want to retain the class of c1$region while being able to use it in queries such as sum(is.na(f2)). Please help.

Upvotes: 0

Views: 4980

Answers (1)

BrodieG
BrodieG

Reputation: 52687

I'm not 100% sure I understand what you are trying to do, but maybe this will help:

c1 <- data.frame(region=c(letters[1:3], NA))
clust <- 1
variable <- "region"

f1 <- get(paste0("c", clust))[[variable]]   # <--- key step
class(f1)
# [1] "factor"
sum(is.na(f1))
# [1] 1

In the key step, we use get to fetch the correct cluster data frame using its name as a character vector, and then we use [[, which unlike $, allows us to use a character variable to specify which column we want.

Upvotes: 2

Related Questions