Home > Enterprise >  Using paste and sum inside a for-loop
Using paste and sum inside a for-loop

Time:02-07

I need to compare a character string to multiple others and tried to do it the following way:

empty = character(0)
ps_2 = c("h2","h3")
ps_3 = c("h3", "h4")
visible = ("h2")

i = 2
ps_t = empty
ps_t <- append(ps_t, sum(visible %in% paste("ps_", i, sep="")))

With the intention to write a loop instead of i = 2, in order to cycle trough ps_2,ps_3,...

However I think it's not working since the paste() command returns a string instead of the character string with the name: ps_2. How can I fix this?

Thanks for the time and effort!

Kind regards,

A fellow datafanatic!

CodePudding user response:

You can use eval in R to convert the string to a variable name. You can find the solution here.

Here's what your code will look like:

ps_t <- c(0, (sum(visible %in% eval(parse(text = paste("ps_", i, sep=""))))))

It will give you a numeric vector.

OR You can use get.

ps_t <- append(0, sum(visible %in% get(paste("ps_", i, sep = ""))))
ps_t

CodePudding user response:

The function you need is get(), which gets the value of the object.

ps_t <- ps_t = NULL

sapply(2:3, function(i) append(ps_t, sum(visible %in% get(paste0("ps_", i)))))

Or simply:

sapply(2:3, function(i) sum(visible %in% get(paste0("ps_", i))))

Output

[1] 1 0
  •  Tags:  
  • Related