Reputation: 2666
I have a character vector that looks like this
vector <- c('a','b','c','d','e')
I have an object in a for-loop that takes input as:
out[a,] <- c(a,b,c,d,e)
Where a-e
are variables with values (for instance, a=0.7
). I would like to feed the out
object some transfomred version of ther vector
object. I've tried
paste(noquote(vector),collapse=',')
However, this just returns
"a,b,c,d,e"
Which is still not useful.
Upvotes: 6
Views: 5802
Reputation: 151
This is very basic question and ate my head almost with a tiny mistake every time. I simplified and created a function in R language.
Here you go buddy!
numbers <- list(2,5,8,9,14,20) #List containing even odd numbers
en<-list() #Initiating even numbers’ list
on<-list() #Initiating odd numbers’ list
#Function creation
separate <- function(x){
for (i in x)
{
ifelse((i%%2)==0, en <- paste(append(en,i, length(en)+1), collapse = ","),
on <- paste(append(on,i, length(on)+1), collapse = ","))
}
message("Even numbers are : ", en)
message("Odd numbers are : ", on)
}
#Passing the function with argument
separate(numbers)
Even numbers are : 2,8,14,20
Odd numbers are : 5,9
Upvotes: 1
Reputation: 38500
You can use mget
to put objects into a named list:
# data
a <- 1; b <- 2; c <- 3; d <- 4; e <- 5
mget(letters[1:5])
$a
[1] 1
$b
[1] 2
$c
[1] 3
$d
[1] 4
$e
[1] 5
or wrap it mget
in unlist
to get a named vector:
unlist(mget(letters[1:5]))
a b c d e
1 2 3 4 5
Upvotes: 5
Reputation: 2722
Reverse the order of the function calls:
noquote(paste(vector, collapse = ','))
This will print [1] a,b,c,d,e
. If you don't like the [1]
use
cat(paste(vector, collapse = ','))
which prints
a,b,c,d,e
Upvotes: 9